/**  
 * @Title: WaimaiServiceImpl.java
 * @Package com.silverbox.sweeporder.service.waimai.impl
 * @author litao
 * @date 2017年12月28日
 */

package com.silverbox.sweeporder.service.waimai.impl;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.silverbox.core.util.*;
import com.silverbox.shopper.entity.*;
import com.silverbox.sweeporder.controller.waimai.entryvo.*;
import com.silverbox.sweeporder.controller.waimai.outvo.*;
import com.silverbox.waimai.dubboApi.payMotion.PayMotionApi;
import com.silverbox.waimai.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.DiscountDetail;
import com.alipay.api.request.KoubeiTradeOrderConsultRequest;
import com.alipay.api.response.KoubeiTradeOrderConsultResponse;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.shopper.dubboApi.alipay.AlipayServiceApi;
import com.silverbox.shopper.dubboApi.alipay.dto.UnDiscountWaimaiItemDTO;
import com.silverbox.shopper.dubboApi.alipay.dto.UndiscountWaimaiDTO;
import com.silverbox.shopper.dubboApi.goods.ShopperGoodsServiceApi;
import com.silverbox.shopper.dubboApi.info.ShopperInfoServiceApi;
import com.silverbox.shopper.dubboApi.order.OrderServiceApi;
import com.silverbox.shopper.entity.extend.CategoryGoods;
import com.silverbox.shopper.entity.extend.DiscountInfo;
import com.silverbox.shopper.entity.extend.InvoiceServiceInfo;
import com.silverbox.shopper.entity.extend.ShopperAndParent;
import com.silverbox.shopper.entity.extend.SystemGoodsExtend;
import com.silverbox.sweeporder.common.AlipayServiceEnvConstants;
import com.silverbox.sweeporder.common.CommConstant;
import com.silverbox.sweeporder.common.CommonConstants;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.common.util.AlipayUtils;
import com.silverbox.sweeporder.common.util.Arith;
import com.silverbox.sweeporder.common.util.KeyGenerateRulesUtils;
import com.silverbox.sweeporder.common.util.OpenAuthTokenAppQuery;
import com.silverbox.sweeporder.common.util.RandomUtil;
import com.silverbox.sweeporder.common.util.RefreshToken;
import com.silverbox.sweeporder.common.util.SweepOrderUtils;
import com.silverbox.sweeporder.controller.index.vo.ReserveBasicInfoVO;
import com.silverbox.sweeporder.controller.index.vo.ShopperConfigExtend;
import com.silverbox.sweeporder.controller.thread.CommonThread;
import com.silverbox.sweeporder.service.index.IndexService;
import com.silverbox.sweeporder.service.redis.RedisService;
import com.silverbox.sweeporder.service.shopcart.ShopCartService;
import com.silverbox.sweeporder.service.waimai.WaimaiOrderService;
import com.silverbox.sweeporder.service.webmsg.WebMsgService;
import com.silverbox.waimai.dubboApi.goodscart.GoodsCartServiceApi;
import com.silverbox.waimai.dubboApi.order.WaimaiServiceApi;
import com.silverbox.waimai.dubboApi.shopper.BusinessInfoApi;
import com.silverbox.waimai.entity.GoodsCartDetail;
import com.silverbox.waimai.entity.SweepClose;
import com.silverbox.waimai.entity.Waimai;
import com.silverbox.waimai.entity.WaimaiBath;
import com.silverbox.waimai.entity.WaimaiItem;
import com.silverbox.waimai.entity.WaimaiItemDetail;
import com.silverbox.waimai.entity.WaimaiOperateRelated;
import com.silverbox.waimai.entity.WaimaiSerialnumber;
import com.silverbox.waimai.entity.extend.GoodsCartAndDetail;
import com.silverbox.waimai.entity.extend.WaimaiExtend;
import com.silverbox.waimai.entity.extend.WaimaiItemExtend;
import com.silverbox.waimai.entity.extend.WaimaiParam;

/**
 * ClassName: WaimaiServiceImpl
 * 
 * @author litao
 * @date 2017年12月28日
 */
@Service
//@Transactional
public class WaimaiOrderServiceImpl implements WaimaiOrderService {

	private static Logger logger = LoggerFactory.getLogger(WaimaiOrderServiceImpl.class);

	@Autowired
	private WaimaiServiceApi waimaiServiceApi;

	@Autowired
	private GoodsCartServiceApi goodsCartServiceApi;

	@Autowired
	private ShopperGoodsServiceApi shopperGoodsServiceApi;

	@Autowired
	private AlipayServiceApi alipayServiceApi;

	@Autowired
	private OrderServiceApi orderServiceApi;

	@Autowired
	private ShopperInfoServiceApi shopperInfoServiceApi;
	
	@Autowired
	private ShopCartService shopCartService;
	
	@Autowired
	private BusinessInfoApi businessInfoApi;
	
	@Autowired
	private RedisService<Serializable, Object> redisServiece;
	
	@Autowired
	private WebMsgService webMsgService;
	
	@Autowired
	private IndexService indexService;

	@Autowired
    private PayMotionApi payMotionApi;

	@Value("${coupon.url}")
	private String couponUrl;

	@Value("${server.url}")
	private String serverUrl;

	@Value("${sweepOrder.APP_ID}")
	private String sweepOrderAppId;

	@Value("${sweepUrl}")
	private String sweepUrl;

	@Value("${invoiceUrl}")
	private String invoiceUrl;

    @Value("${invoiceServiceUrl}")
    private String invoiceServiceUrl;

	@Value("${serviceWindowUrl}")
	private String serviceWindowUrl;

	@Value("${koubeiUploadUrl}")
	private String koubeiUploadUrl;

	@Value("${uploadOrderFlag}")
	private String uploadOrderFlag;

	@Value("${uploadUrl}")
	private String uploadUrl;
	
	@Value("${openIntelligence.url}")
	private String openIntelligenceUrl;

	@Value("${API_SERVICE}")
	private String API_SERVICE;
	
	@Value("${ORDER_LOCK_PAY_TIME}")
	private Integer order_lock_pay_time;

	@Value("${marketing.url}")
    public String marketingUrl;


	@SuppressWarnings("unchecked")
	@Override
	public WaimaiExtend saveWaimaiOrder(WaimaiExtend waimai, List<GoodsCartAndDetail> goodsList, CreateWaimaiEntryDto createWaimai,
			ThirdUserInfo thirdUserInfo, Double bagPrice,Double boxPrice,String batchNo) {

		List<WaimaiItemExtend> waimaiItem = new ArrayList<WaimaiItemExtend>();
		Map<String, Object> itemMap = new HashMap<String, Object>();
		ShopperAndParent shopper = shopperInfoServiceApi.getShopperAndParent(createWaimai.getStoreId());
		if(shopper!=null){
			waimai.setShopperId(shopper.getParentId());
			waimai.setShopperName(shopper.getParentInfo().getNick());
			waimai.setShopName(shopper.getNick());
			waimai.setShopAddress(shopper.getAddress());
			waimai.setShopContactPhone(shopper.getContactPhone());
			if (shopper.getMinLogo() != null) {
				waimai.setShopLogo(shopper.getMinLogo());
			} else {
				waimai.setShopLogo("/res/css/custom/shop_min.png");
			}
		}
		//保存订单项及餐具费、打包费、服务费订单项
		itemMap = saveItem(waimai, goodsList, bagPrice, createWaimai, thirdUserInfo, new Integer(0), boxPrice,batchNo);
        double totalOriginalPrice = itemMap.get("totalOriginalPrice") == null ? 0.0d : (double) itemMap.get("totalOriginalPrice");
		Double totalPrices = itemMap.get("totalPrices") == null ? 0.0 : (double) itemMap.get("totalPrices");
        double boxTotalPrice = itemMap.get("boxTotalPrice") == null ? 0.0d : (double) itemMap.get("boxTotalPrice");
        double bagTotalPrice = itemMap.get("bagTotalPrice") == null ? 0.0d : (double) itemMap.get("bagTotalPrice");
        //桌台 餐盒+打包
        waimaiItem = (List<WaimaiItemExtend>) itemMap.get("waimaiItem");
		//口碑正餐后付没有餐具费、打包费
		if(!new Long(103).equals(waimai.getOuterSupportId())){
            waimai.setOtherPrice(Arith.add(boxTotalPrice,bagTotalPrice));
            totalPrices = Arith.add(totalPrices, boxTotalPrice);// 订单总价加上其它费用
            totalOriginalPrice = Arith.add(totalOriginalPrice,boxTotalPrice);
		}
		waimai.setTotalPrice(totalPrices);
		waimai.setOriginalPrice(totalOriginalPrice);
		waimai.setItems(waimaiItem);
		waimai.setCreateTime(new Date());
		waimai.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
		waimai.setTotalPay(0.0);
		//口碑正餐先付 
		if(new Long(103).equals(waimai.getOuterSupportId())){
			waimai.setTotalFee(totalPrices);
		}
		//获取redis店铺配置信息
		Object config = redisServiece.getObj(waimai.getShopId()+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(waimai.getShopId());
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		//创建订单同时，删除购物车放到同一个事物中
		waimaiServiceApi.saveWaimai(waimai, shopperConfigExt,createWaimai);
		logger.info("创建新订单时生成的订单号++++++++++++++orderNum="+waimai.getOrderNum()+"++++buyerId="+thirdUserInfo.getThirdUserId()+"++tableInfo="+waimai.getTableNum()+"++goodsCart="+(goodsList==null?null:goodsList.size()));
		//口碑正餐后付订单
		if(new Long(103).equals(waimai.getOuterSupportId())){
			// 下单新增订单批次表
			WaimaiBath waimaiBath = new WaimaiBath();
			// 银盒子商家ID
			waimaiBath.setShopId(waimai.getShopperId());
			// 银盒子门店ID
			waimaiBath.setStoreId(waimai.getShopId());
			// 银盒子订单号
			waimaiBath.setOrderNum(waimai.getOrderNum());
			// 批次号
			if(itemMap.get("batchNo")!=null){
				waimaiBath.setBatchNo(String.valueOf(itemMap.get("batchNo")));
			}
			// 状态（0：初始状态 1：已接单 2：已拒单）
			waimaiBath.setStatus(Constants.orderStatus.STATUS_ZERO.getValue());
			// 支付状态（0：未支付 1：已支付）
			waimaiBath.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
			// 订单批次类型编码（SYS：银盒子 KB：口碑）
			waimaiBath.setTypeCode("SYS");
			// 订单总价
			waimaiBath.setTotalAmount(totalPrices);
			// 创建时间
			waimaiBath.setCreateTime(new Date());
			// 修改时间
			waimaiBath.setUpdateTime(new Date());
			waimaiServiceApi.saveOrUpdateWaimaiBath(waimaiBath);
		}
		return waimai;
	}

	@SuppressWarnings("unchecked")
	@Override
	public WaimaiExtend saveWaimaiOrderAddFood(WaimaiExtend waimai, List<GoodsCartAndDetail> goodsList,
                                               CreateWaimaiEntryDto createWaimai, ThirdUserInfo thirdUserInfo, Double bagPrice, Double boxPrice, String batchNo,ShopperConfigExtend shopperConfigExtend) {
		List<WaimaiItemExtend> waimaiItem = new ArrayList<WaimaiItemExtend>();
		Map<String, Object> itemMap = new HashMap<String, Object>();
		//加菜之前的总价
		double beforePrice = 0.0d;
		if(new Long(103).equals(waimai.getOuterSupportId()) && waimai.getTotalPrice()!=null){
			beforePrice = waimai.getTotalPrice();
		}
        waimai.setUid(createWaimai.getUid());

        itemMap = saveItem(waimai, goodsList, bagPrice, createWaimai, thirdUserInfo, 1,boxPrice,batchNo);
		double totalPrice = Double.valueOf(Optional.ofNullable(itemMap.get("totalPrices")).orElse(0D).toString());
		double boxTotalPrice = Double.valueOf(Optional.ofNullable(itemMap.get("boxTotalPrice")).orElse(0D).toString());
        double bagTotalPrice = Double.valueOf(Optional.ofNullable(itemMap.get("bagTotalPrice")).orElse(0D).toString());
        double totalOriginalPrice =  Double.valueOf(Optional.ofNullable(itemMap.get("totalOriginalPrice")).orElse(0D).toString());

        waimai.setOriginalPrice(totalOriginalPrice);
        waimaiItem = (List<WaimaiItemExtend>) itemMap.get("waimaiItem");
		
		waimai.setPeopleNumber(createWaimai.getPeopleNumber());
        waimai.setOtherPrice(Arith.add(boxTotalPrice,bagTotalPrice));
		//口碑正餐后付不计算餐具费、打包费
		if(!new Long(103).equals(waimai.getOuterSupportId())){
			totalPrice = Arith.sub(totalPrice,boxTotalPrice); // 加菜前，总价-其他费用 加菜后，订单总价(不包括新加菜的价格)
            waimai.setOtherPrice(boxTotalPrice);
//			totalPrice = Arith.add(totalPrice, boxTotalPrice); //
		}
		waimai.setTotalPrice(totalPrice);
//		waimai.setOriginalPrice(totalOriginalPrice);
		if (!new Integer(1).equals(waimai.getIsOut())) {
			waimai.setOtherPrice(Arith.add(boxTotalPrice,bagTotalPrice));
		}
        List<WaimaiItemExtend> oldItems = waimai.getItems();
        waimai.setItems(waimaiItem);
		//口碑正餐后付
		if(new Long(103).equals(waimai.getOuterSupportId())){
			//实际支付金额
			waimai.setTotalFee(totalPrice);
		}
		logger.info("订单项加菜时的订单号================="+waimai.getOrderNum());
		waimaiServiceApi.addDish(waimai,oldItems,createWaimai,shopperConfigExtend);
		//获取redis店铺配置信息
		Object config = redisServiece.getObj(waimai.getShopId()+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(waimai.getShopId());
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		//口碑正餐后付订单
		if(new Long(103).equals(waimai.getOuterSupportId())){
			// 下单新增订单批次表
			WaimaiBath waimaiBath = new WaimaiBath();
			// 银盒子商家ID
			waimaiBath.setShopId(waimai.getShopperId());
			// 银盒子门店ID
			waimaiBath.setStoreId(waimai.getShopId());
			// 银盒子订单号
			waimaiBath.setOrderNum(waimai.getOrderNum());
			// 批次号
			if(itemMap.get("batchNo")!=null){
				waimaiBath.setBatchNo(String.valueOf(itemMap.get("batchNo")));
			}
			// 状态（0：初始状态 1：已接单 2：已拒单）
			waimaiBath.setStatus(Constants.orderStatus.STATUS_ZERO.getValue());
			// 支付状态（0：未支付 1：已支付）
			waimaiBath.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
			// 订单批次类型编码（SYS：银盒子 KB：口碑）
			waimaiBath.setTypeCode("SYS");
			// 订单总价 加菜时为每次加的菜的总价
			waimaiBath.setTotalAmount(Arith.sub(totalPrice,beforePrice));
			// 创建时间
			waimaiBath.setCreateTime(new Date());
			// 修改时间
			waimaiBath.setUpdateTime(new Date());
			waimaiServiceApi.saveOrUpdateWaimaiBath(waimaiBath);
		}
		//清除必选菜
		Integer mustOrder = null;
		if (StringUtils.isNotEmpty(waimai.getTableNum())) {
			if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
				goodsCartServiceApi.removeGoodsCartByTableNoAndBuyerId(waimai.getShopId(), waimai.getTableNum(),mustOrder, waimai.getBuyerId());
			} else {
				goodsCartServiceApi.removeGoodsCartByTableNo(waimai.getShopId(), waimai.getTableNum(),mustOrder);
			}
		} else {
			goodsCartServiceApi.removeGoodsCartByBuyerId(waimai.getShopId(), waimai.getBuyerId(),mustOrder);
		}
		return waimai;
	}

	private Map<String, Object> saveItem(WaimaiExtend waimai, List<GoodsCartAndDetail> goodsList,
                                         Double bagPrice, CreateWaimaiEntryDto createWaimai, ThirdUserInfo thirdUserInfo, Integer type, Double boxPrice, String batchNo) {
		
		List<WaimaiItemExtend> waimaiItem = new ArrayList<WaimaiItemExtend>();
		Byte num = 0;
		double totalPrices = 0.0;
		double totalOriginalPrice = 0D;
		//打包商品总数量
		double bagtotalCount = 0.0;
		//type为1表示加菜

		if (new Integer(1).equals(type)) {
			totalPrices = waimai.getTotalPrice();
            totalOriginalPrice = waimai.getOriginalPrice();
		}
		StringBuffer disItemIds = new StringBuffer("");
		StringBuffer disItemTypes = new StringBuffer("");
		WaimaiItemExtend item = null;
		for (GoodsCartAndDetail goods : goodsList) {
		    logger.info("boxPrice == "+boxPrice);
		    logger.info("goodsCart add order:"+goods.getGoodsName() + ",buyPrice="+goods.getBuyPrice());
			item = new WaimaiItemExtend();
			item.setCouponCode(goods.getCouponCode());
			item.setIsPrint(Byte.parseByte("0"));
			item.setGive(0.0d);
			item.setBagPrice(0.0d);
			if (new Integer(1).equals(goods.getIsWeight())) {
				item.setBuyCount(0.0d);
			} else {
				item.setBuyCount(goods.getBuyCount());
			}
			item.setBuyPrice(goods.getBuyPrice());
			item.setOriginalPrice(goods.getOriginalPrice());
            item.setPropPrice(goods.getPropPrice());
			item.setGoodsId(goods.getGoodsId());

			item.setGoodsImg(goods.getGoodsImg());
			item.setGoodsName(goods.getGoodsName());
			item.setRemark(goods.getRemark());
			//20200603会员价item便于优惠预咨询
			item.setMemberPrice(!Utils.isEmpty(createWaimai.getMemberId()) && !Utils.isEmpty(goods.getMemberPrice()) ? goods.getMemberPrice() : null);
            //20200626付费会员会员价
//            item.setMemberPrice(goods.getMemberPrice());
            //存储优惠信息、如果couponCode不为空 buyerPrice已为优惠后价格
            if(!Utils.isEmpty(goods.getCouponCode())){
                //优惠差价 = 原价 - 优惠后价格
                item.setPromotionName(goods.getPromotionName());
//                item.setPromotionPrice(Arith.mul(goods.getOriginalPrice(),goods.getBuyPrice()));
            }
			if (new Integer(1).equals(type)) {
				item.setWaimaiId(waimai.getId());
				item.setIsAdd(1);
			} else {
				item.setIsAdd(0);
				item.setNum(++num);
			}
			item.setPromotionDesc(goods.getPromotionDesc());
			if (StringUtils.isNotEmpty(goods.getPropIds())) {
				item.setPropId(changePropIds(changePropString(goods.getPropIds())));
				item.setPropDesc(changePropNames(changePropString(goods.getPropNames())));// 商品属性
			} else {
				item.setPropId(null);
				item.setPropDesc(null);
			}
			item.setPromotionName(goods.getPromotionName());
			item.setPromotionType(goods.getPromotionType());
			item.setSizeType(goods.getSizeType());
			item.setCategoryName(goods.getCategoryName());
			item.setGoodsDesc(goods.getGoodsDesc());// 新增打包属性 --zfy
			item.setIsWeight(goods.getIsWeight());// 新增是否是称重商品 --ywc
			item.setSizeId(goods.getSizeId());// 添加商品属性 add yl
			item.setIsNotshowSize(goods.getIsNotshowSize());
			item.setPropValue(goods.getPropPrice()==null?"0.0":String.valueOf(goods.getPropPrice()));// 添加加料价格
			item.setIsPackage(goods.getIsPackage());
			item.setStoreId(goods.getShopperId());
			item.setCreateTime(new Date());
			item.setOrderNum(waimai.getOrderNum());
			item.setThirdUserInfoId(thirdUserInfo.getId());
			item.setMustOrder(goods.getMustOrder());
			item.setMemberPrice(goods.getMemberPrice());  // 新增会员价 --hyc
			//添加属性价格
			item.setPropPrice(goods.getPropPrice()==null?0.0:goods.getPropPrice());
			//口碑正餐后付订单
			if(new Long(103).equals(waimai.getOuterSupportId()) && !StringUtils.isEmpty(batchNo)){
				item.setBatchNo(batchNo);
				// 菜品支付状态
				item.setPayStatus(0);
				// 菜品接单状态
				item.setStatus(0);
			}
			// add by yxy 2019年3月18日 14:37:22 订单菜品唯一编号
			item.setGuid(Utils.createUUID());
			// 操作人员类型
			item.setOperatorType(CommonConstants.WaimaiOperatorType.CUSTOMER.getValue());
			// 操作人员员工号 扫码点餐不存
			item.setOperatorNum(null);
			// 操作人员的昵称或者名称
			item.setOperatorNick(thirdUserInfo.getNickName() == null ? "吃货" : thirdUserInfo.getNickName());
			
			if (goods.getIsPackage() != null
					&& (new Integer(2).equals(goods.getIsPackage()) || new Integer(1).equals(goods.getIsPackage()))) {
				List<GoodsCartDetail> goodsDetails = goods.getDetails();
				WaimaiItemDetail itemDetail = null;
				for (GoodsCartDetail goodsDetail : goodsDetails) {
					itemDetail = new WaimaiItemDetail();
					itemDetail.setOrderNum(waimai.getOrderNum());
					itemDetail.setGoodsGroupId(goodsDetail.getGoodsGroupId());
					itemDetail.setGoodsGroupName(goodsDetail.getGoodsGroupName());
					itemDetail.setGoodsId(goodsDetail.getGoodsId());
					itemDetail.setGoodsName(goodsDetail.getGoodsName());
					itemDetail.setGoodsImg(goodsDetail.getGoodsImg());
					itemDetail.setSizeId(goodsDetail.getSizeId());
					itemDetail.setSizeType(goodsDetail.getSizeType());
					itemDetail.setOriginalPrice(goodsDetail.getOriginalPrice());
					if (StringUtils.isNotEmpty(goodsDetail.getPropIds())) {
						itemDetail.setPropIds(changePropNames(changePropString(goodsDetail.getPropIds())));
						itemDetail.setPropNames(changePropNames(changePropString(goodsDetail.getPropNames())));
					} else {
						itemDetail.setPropIds(null);
						itemDetail.setPropNames(null);
					}
					itemDetail.setPropPrice(goodsDetail.getPropPrice());
					itemDetail.setBuyCount(goodsDetail.getBuyCount());
					itemDetail.setBuyPrice(goodsDetail.getBuyPrice());
					itemDetail.setCategoryId(goodsDetail.getCategoryId());
					itemDetail.setCategoryName(goodsDetail.getCategoryName());
					itemDetail.setSuitState(goodsDetail.getSuitState());
					itemDetail.setIsNotshowSize(goodsDetail.getIsNotshowSize());
					itemDetail.setIsRequre(goodsDetail.getIsRequre());
					// add by yxy 2019年3月18日 14:37:22 订单菜品唯一编号
					itemDetail.setGuid(Utils.createUUID());
					// add by hyc 2019年4月10日17:58:45 加价做法明细
					itemDetail.setPropDetail(goodsDetail.getPropDetail());
					item.getDetails().add(itemDetail);
				}
			}
			// 查询优惠商品
			if (StringUtils.isNotEmpty(goods.getDiscountItemId())) {
				disItemIds.append(goods.getDiscountItemId() + ",");
				disItemTypes.append(goods.getItemType() + ",");
			}
			//称重商品不计算价格
			if(!new Integer(1).equals(goods.getIsWeight())){
				// 计算菜品总金额
                double buyPrice = !Utils.isEmpty(createWaimai.getMemberId()) && !Utils.isEmpty(goods.getMemberPrice()) ? goods.getMemberPrice() : goods.getBuyPrice();
                //20200625付费会员会员价
//                double buyPrice = goods.getMemberPrice();
                totalPrices = Arith.add(totalPrices, Arith.mul(goods.getBuyCount(), buyPrice));
                double originalPrice = Arith.mul(goods.getBuyCount(),goods.getOriginalPrice());
//                double originalPrice = Arith.mul(goods.getBuyCount(),Utils.isEmpty(goods.getCouponCode()) ? goods.getOriginalPrice() : buyPrice);
                logger.info("goods getPropPrice = " +goods.getPropPrice());
                //页面 原价字段购物车未合并propPrice，此时需要合并方便订单统计原价数据
                if (!new Integer(1).equals(goods.getIsPackage()) && !new Integer(2).equals(goods.getIsPackage())){
                    double propPrice = Utils.isEmpty(goods.getPropPrice()) ? 0D : goods.getPropPrice();
                    originalPrice = Arith.add(originalPrice,Arith.mul(goods.getBuyCount(),propPrice));
                }
                totalOriginalPrice = Arith.add(totalOriginalPrice, originalPrice);
            }
			
			// 计算打包费   口碑正餐后付不计算餐具费、打包费
			if (bagPrice > 0 && !new Long(103).equals(waimai.getOuterSupportId())) {
				if (waimai.getIsOut() != null && new Integer(1).equals(waimai.getIsOut())) {
					totalPrices = Arith.add(totalPrices, Arith.mul(goods.getBuyCount(), bagPrice));
					totalOriginalPrice = Arith.add(totalOriginalPrice, Arith.mul(goods.getBuyCount(), bagPrice));

                    double itemBagPrice = Arith.mul(goods.getBuyCount(), bagPrice);
                    item.setBagPrice(itemBagPrice);
					bagtotalCount = Arith.add(goods.getBuyCount(),bagtotalCount);
				} else {
					if ("打包".equals(goods.getGoodsDesc())) {
						totalPrices = Arith.add(totalPrices, Arith.mul(goods.getBuyCount(), bagPrice));

                        totalOriginalPrice = Arith.add(totalOriginalPrice, Arith.mul(goods.getBuyCount(), bagPrice));

                        double itemBagPrice = Arith.mul(goods.getBuyCount(), bagPrice);
						item.setBagPrice(itemBagPrice);
						bagtotalCount = Arith.add(goods.getBuyCount(),bagtotalCount);
					}
				}
			}
			// add by hyc 2019年4月10日17:58:45 加价做法明细
			if(null != goods.getIsPackage() && goods.getIsPackage() != 2){
				item.setPropDetail(goods.getPropDetail());
			}
			waimaiItem.add(item);
		}
		//餐具费总价
		double boxTotalPrice = 0.0;
		if(!new Long(103).equals(waimai.getOuterSupportId())){
			
			
			List<WaimaiItemExtend> waimaiItems= null;
			//加菜
			if(new Integer(1).equals(type)){
				waimaiItems = new ArrayList<WaimaiItemExtend>(waimai.getItems());
			}else{
				waimaiItems = new ArrayList<WaimaiItemExtend>(waimaiItem);
			}
			logger.info("餐具费订单项生成+++++++++++waimaiItems表示新生成的+++waimaiItems=" + (waimaiItems == null ? null : waimaiItems.size())
					+ "++++++++++items表示加菜之前的++itmes=" + (waimai.getItems() == null ? null : waimai.getItems().size())+"++type为1表示加菜++type="+type);
			//生成餐具费、打包费订单项
			List<String> systemGoods = new ArrayList<String>();
			systemGoods.add(CommConstant.SYSTEM_BAG_GOODS);
			systemGoods.add(CommConstant.SYSTEM_BOX_GOODS);
			List<CategoryGoods> bagGoods= shopperGoodsServiceApi.getSystemGoodsInfo(systemGoods);
			//判断是新增还是修改餐具费、打包费订单项
			Map<String,Boolean> sysMap = new HashMap<String,Boolean>();
			if(!CollectionUtils.isEmpty(bagGoods) && !CollectionUtils.isEmpty(waimaiItems)){
				for(CategoryGoods goods:bagGoods){
					//判断是否满足打包、餐具订单项生成条件
					if ((CommConstant.SYSTEM_BAG_GOODS.equals(goods.getInCode()) && bagPrice > 0 && (bagtotalCount > 0 || new Integer(1).equals(type)))
							|| (CommConstant.SYSTEM_BOX_GOODS.equals(goods.getInCode()) && boxPrice > 0
									&& waimai.getPeopleNumber() > 0 && waimai.getIsOut() != 1)) {
						for(WaimaiItemExtend i:waimaiItems) {
							if (CommConstant.SYSTEM_BAG_GOODS.equals(goods.getInCode())
									&& (CommConstant.SYSTEM_BAG_GOODS).equals(i.getGoodsDesc())) {
								item = new WaimaiItemExtend();
								if(new Integer(1).equals(type) && bagtotalCount==0.0d){
									item.setBuyCount(i.getBuyCount());
								}else{
									item.setBuyCount(Arith.add(i.getBuyCount(), bagtotalCount));
								}
								if(new Integer(1).equals(type) && i.getItemId()!=null){
									item.setItemId(i.getItemId());
								}
								item.setBuyPrice(bagPrice);
								item.setOriginalPrice(bagPrice);
								item.setGoodsId(goods.getGoodsId());
								item.setGoodsName(goods.getGoodsName());
								item.setNum(++num);
								item.setIsWeight(goods.getIsWeight());//新增是否是称重商品 --ywc
								item.setIsPackage(goods.getIsPackage());
								item.setGoodsDesc(goods.getInCode());
								item.setWaimaiId(waimai.getId());
								//打包费的唯一guid（加菜）
								item.setGuid(Utils.createUUID());
								waimaiItem.add(item);
								sysMap.put("bag",true);
								continue;
							}
							if (CommConstant.SYSTEM_BOX_GOODS.equals(goods.getInCode())
									&& CommConstant.SYSTEM_BOX_GOODS.equals(i.getGoodsDesc())) {
								item = new WaimaiItemExtend();
								//计算人数改变
								double boxNum = Arith.sub(createWaimai.getPeopleNumber(),waimai.getPeopleNumber());
								//计算餐具费item项中数量变化
                                boxTotalPrice = Arith.mul(boxNum,boxPrice);
                                logger.info("boxTotalPrice NEW="+boxTotalPrice);
                                item.setBuyCount(i.getBuyCount());
								if(new Integer(1).equals(type) && i.getItemId()!=null){
									item.setItemId(i.getItemId());
								}
								item.setBuyPrice(boxPrice);
								item.setOriginalPrice(boxPrice);
								item.setGoodsId(goods.getGoodsId());
								item.setGoodsName(goods.getGoodsName());
								item.setNum(++num);
								item.setIsWeight(goods.getIsWeight());//新增是否是称重商品 --ywc
								item.setIsPackage(goods.getIsPackage());
								item.setGoodsDesc(goods.getInCode());
								item.setWaimaiId(waimai.getId());
								//餐具费的唯一guid（加菜）
								item.setGuid(Utils.createUUID());
								waimaiItem.add(item);
								sysMap.put("box", true);
								continue;
							}
						}
						if((CommConstant.SYSTEM_BAG_GOODS.equals(goods.getInCode()) && bagPrice > 0 && bagtotalCount > 0) && (sysMap.get("bag")==null || !sysMap.get("bag"))){
							item = new WaimaiItemExtend();
							item.setBuyCount(bagtotalCount);
							item.setBuyPrice(bagPrice);
							item.setOriginalPrice(bagPrice);
							item.setGoodsId(goods.getGoodsId());
							item.setGoodsName(goods.getGoodsName());
							item.setNum(++num);
							item.setIsWeight(goods.getIsWeight());//新增是否是称重商品 --ywc
							item.setIsPackage(goods.getIsPackage());
							item.setGoodsDesc(goods.getInCode());
							item.setWaimaiId(waimai.getId());
							//打包费的唯一guid
							item.setGuid(Utils.createUUID());
							waimaiItem.add(item);
						}
						if((CommConstant.SYSTEM_BOX_GOODS.equals(goods.getInCode()) && boxPrice > 0
								&& waimai.getPeopleNumber() > 0 && waimai.getIsOut() != 1) && (sysMap.get("box")==null || !sysMap.get("box"))){
							item = new WaimaiItemExtend();
							boxTotalPrice = Arith.mul(boxPrice, waimai.getPeopleNumber());
							logger.info("boxTotalPrice="+boxTotalPrice);
							item.setBuyCount(Double.valueOf(waimai.getPeopleNumber()));
							item.setBuyPrice(boxPrice);
							item.setOriginalPrice(boxPrice);
							item.setGoodsId(goods.getGoodsId());
							item.setGoodsName(goods.getGoodsName());
							item.setNum(++num);
							item.setIsWeight(goods.getIsWeight());//新增是否是称重商品 --ywc
							item.setIsPackage(goods.getIsPackage());
							item.setGoodsDesc(goods.getInCode());
							item.setWaimaiId(waimai.getId());
							//打包费的唯一guid
							item.setGuid(Utils.createUUID());
							waimaiItem.add(item);
						}
					}
				}
			}
		}
		//创建订单时新增服务费、在线订单暂不支持
		if(!new Integer(1).equals(type) && !Constants.orderOutSupportId.ONLINE_ORDER.getValue().equals(waimai.getOuterSupportId()) && !Constants.orderOutSupportId.WAIMAI_ORDER.getValue().equals(waimai.getOuterSupportId())){
			//获取店铺系统级商品配置信息  
			List<SystemGoodsExtend> systemGoodsList = shopperGoodsServiceApi.getShopSystemGoods(waimai.getShopId(), waimai.getShopperId(), waimai.getTableUid(),DateUtils.getDayofweek());
			if(!CollectionUtils.isEmpty(systemGoodsList)){
				for(SystemGoodsExtend goods:systemGoodsList){
					//新增服务费订单项，只在创建新订单的时候生成，加菜订单不管
					if((CommConstant.SYSTEM_FWF_GOODS.equals(goods.getInCode())) && goods.getPrice()>0){
						try {
							Date date =new Date();
							String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();// 当前年月日
							SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
							Date startTime = sd.parse(currDate+" "+goods.getStartTime());
							Date endTime = sd.parse(currDate+" "+goods.getEndTime());
							if(date.after(startTime) && date.before(endTime)){
								item = new WaimaiItemExtend();
								item.setBuyCount(1d);
								item.setBuyPrice(goods.getPrice());
								item.setOriginalPrice(goods.getPrice());
								item.setGoodsId(goods.getGoodsId());
								item.setGoodsName(goods.getGoodsName());
								item.setNum(++num);
								item.setIsWeight(goods.getIsWeight());//新增是否是称重商品 --ywc
								item.setIsPackage(goods.getIsPackage());
								item.setGoodsDesc(goods.getInCode());
								item.setWaimaiId(waimai.getId());
								//口碑正餐后付订单
								if(new Long(103).equals(waimai.getOuterSupportId()) && !StringUtils.isEmpty(batchNo)){
									item.setBatchNo(batchNo);
									// 菜品支付状态
									item.setPayStatus(0);
									// 菜品接单状态
									item.setStatus(0);
								}
								waimaiItem.add(item);
								totalPrices = Arith.add(totalPrices,goods.getPrice());
                                logger.info("totalOriginalPrice 4=="+totalOriginalPrice);

                                totalOriginalPrice = Arith.add(totalOriginalPrice,goods.getPrice());
								break;
							}
						} catch (ParseException e) {
							logger.error("新增订单项服务费异常===========waimai="+JSONObject.toJSONString(waimai)+"系统级商品信息========systemGoodsList="+JSONObject.toJSONString(systemGoodsList));
							e.printStackTrace();
						}
					}
				}
			}
		}
		// 支付宝领取优惠券
		if (null != thirdUserInfo && thirdUserInfo.getSource() == 1) {
			if (StringUtils.isNotEmpty(disItemIds.toString()) && ",".equals(disItemIds.toString()
					.substring(disItemIds.toString().length() - 1, disItemIds.toString().length()))) {
				disItemIds.deleteCharAt(disItemIds.toString().length() - 1);
				disItemTypes.deleteCharAt(disItemTypes.toString().length() - 1);
			}
			if (StringUtils.isNotEmpty(disItemIds.toString()) && StringUtils.isNotEmpty(disItemTypes.toString())) {
				String userId = thirdUserInfo.getThirdUserId().length() > thirdUserInfo.getUserId().length()
						? thirdUserInfo.getUserId()
						: thirdUserInfo.getThirdUserId();
				receiveCoupon(createWaimai.getStoreId(), userId, disItemIds.toString(), disItemTypes.toString(), couponUrl);
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if(!StringUtils.isEmpty(batchNo)){
			map.put("batchNo",batchNo);
		}
        map.put("waimaiItem", waimaiItem);
		map.put("totalPrices", totalPrices);
		map.put("totalOriginalPrice",totalOriginalPrice);
		map.put("boxTotalPrice", boxTotalPrice);
        map.put("bagTotalPrice", Arith.mul(bagPrice,bagtotalCount));
        logger.info("saveItem操作订单="+map.toString());
		return map;
	}

	/**
	 * 去掉propIds或者propNames的头尾+或_
	 * 
	 * @param propStr
	 * @return
	 */
	private String changePropString(String propStr) {
		if (StringUtils.isEmpty(propStr)) {
			return propStr;
		}
		propStr = propStr.replaceAll("_", "+");
		if (propStr.startsWith("+")) {
			propStr = propStr.substring(1, propStr.length());
		}
		if (propStr.endsWith("+")) {
			propStr = propStr.substring(0, propStr.length() - 1);
		}
		propStr = propStr.replaceAll("x", "×");
		return propStr;
	}

	/**
	 * 去掉propIds中的x（云POS接单，不需要在propdIds中拼接加料数量）
	 * @return
	 */
	private String changePropIds(String propIds) {
		if (StringUtils.isEmpty(propIds) || !propIds.contains("×")) {
			return propIds;
		}
		String[] propIdArr = propIds.split("\\+");
		String newPropIds = "";
		for (int i = 0; i < propIdArr.length; i++) {
			if (propIdArr[i].contains("×")) {
				newPropIds = ("".equals(newPropIds) ? "" : (newPropIds + "+"))
						+ propIdArr[i].substring(0, propIdArr[i].lastIndexOf("×"));
			} else {
				newPropIds = ("".equals(newPropIds) ? "" : (newPropIds + "+")) + propIdArr[i];
			}
		}
		return newPropIds;
	}

	/**
	 * 去掉propNames中的x（云POS接单，不需要在propdIds中拼接加料数量）
	 * 
	 * @param
	 * @return
	 */
	private String changePropNames(String propNames) {
		if (StringUtils.isEmpty(propNames)) {
			return propNames;
		}
		String[] propNameArr = propNames.split("\\+");
		String newPropNames = "";
		for (int i = 0; i < propNameArr.length; i++) {
			if (propNameArr[i].contains("×")) {
				String[] propNameAndCountArr = propNameArr[i].split("×");
				if (new Integer(1).equals(Integer.valueOf(propNameAndCountArr[1]))) { // 加料数量为1的时候，去掉x1
					newPropNames = ("".equals(newPropNames) ? "" : (newPropNames + "+")) + propNameAndCountArr[0];
				} else {
					newPropNames = ("".equals(newPropNames) ? "" : (newPropNames + "+")) + propNameArr[i];
				}
			} else {
				newPropNames = ("".equals(newPropNames) ? "" : (newPropNames + "+")) + propNameArr[i];
			}
		}
		return newPropNames;
	}

	// 口碑领券
	public static CoreResponse<String> receiveCoupon(Integer shopperId, String userId, String disItemIds,
			String disItemTypes, String couponUrl) {
		Map<String, String> nameValuePair = new HashMap<String, String>();
		nameValuePair.put("shopperId", shopperId.toString());
		nameValuePair.put("userId", userId);
		nameValuePair.put("itemIds", disItemIds);
		nameValuePair.put("itemTypes", disItemTypes);
		CoreResponse<String> result = HttpUtils.doPostForm(couponUrl + "/kouberajax/benefitSend.htm", nameValuePair);
		return result;
	}

	@Override
	public void updateWaimaiStauts(Waimai waimai) {
		waimaiServiceApi.updateWaimai(waimai);
	}

	@Override
	public Integer getOrderSeq(Integer storeId, int orderType) {
		// return orderServiceApi.updateAndGetOrderSeq(storeId, num);
		// 新增获取订单号存储过程替换成sql查询 update by hyc 2019年5月20日16:24:15
		Shopper shopper = shopperInfoServiceApi.selectIndex(storeId, orderType);
		if (Utils.isEmpty(shopper)) {
			return 0;
		}
		String nowDate = CalendarUtil.formatDateByString(new Date());
		String shopHours = CalendarUtil.formatDateByString(shopper.getShopHours());
		// orderType 0 为in_index 1为out_index   shopper.getInIndex()为空初始化值为1 不为空值则+1
		Integer index = orderType == 0 ? (shopper.getInIndex() == null ? 1 : (shopper.getInIndex() + 1)) 
				: (shopper.getOutIndex() == null ? 1 : (shopper.getOutIndex() + 1));
		// 对比时间	如果是同一天，更新in_index或out_index；如果不是同一天，初始化out_index，in_index，shop_hours
		if (Utils.isEmpty(shopper.getShopHours()) || !nowDate.equals(shopHours)) {
			shopperInfoServiceApi.updateIndex(storeId);
		} else {
			shopperInfoServiceApi.updateIndexs(storeId, orderType, index);
		}
		return index;
	}

	@Override
	public Waimai getMyOrderStatus(Integer storeId, String tableName, String buyerId,Integer clientOrderMode) {
		WaimaiParam waimaiParam = new WaimaiParam();
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		waimaiParam.setStoreId(storeId);
		waimaiParam.setStartDate(startDate);
		waimaiParam.setEndDate(endDate);
		Waimai waimai = null;
		//获取redis店铺配置信息
		Object config = redisServiece.getObj(storeId+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		//查询在线订单订单信息
		if(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode) || Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().equals(clientOrderMode)){
//			waimaiParam.setOutSupportId(Long.parseLong(clientOrderMode.toString()));
            List<Integer> inOuterSupportIds = new LinkedList<>();
            inOuterSupportIds.add(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue());
            inOuterSupportIds.add(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue());
            waimaiParam.setInOuterSupportIds(inOuterSupportIds);

			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
			waimaiParam.setIsHexiao(0);
			waimaiParam.setBuyerId(buyerId);
			waimai = waimaiServiceApi.getWaimaiByBuyerId(waimaiParam);
		//查询扫码下单订单信息
		}else{
			//是否开通口碑后付
			if(shopperConfigExt!=null && new Integer(1).equals(shopperConfigExt.getKoubeiDinner())){
				waimaiParam.setOutSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
			}else{
				if(shopperConfigExt!=null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())){
					waimaiParam.setBuyerId(buyerId);
				}
				waimaiParam.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
			}
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_THREE.getValue());
			waimaiParam.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
			if (StringUtils.isNotEmpty(tableName)) {
				waimaiParam.setTableNum(tableName);
				waimai = waimaiServiceApi.getWaimaiByTableNum(waimaiParam);
			} else {
				waimaiParam.setBuyerId(buyerId);
				waimai = waimaiServiceApi.getWaimaiByBuyerId(waimaiParam);
			}
		}
		return waimai;
	}

	@Override
	public WaimaiExtend getWaimaiDeatils(Integer storeId, String tableName, String buyerId,Integer clientOrderMode, ShopperConfigExtend shopperConfig) {
		WaimaiParam waimaiParam = new WaimaiParam();
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		waimaiParam.setStoreId(storeId);
		waimaiParam.setStartDate(startDate);
		waimaiParam.setEndDate(endDate);
		Shopper shopper = shopperInfoServiceApi.getShopper(storeId);
		WaimaiExtend waimai = new WaimaiExtend();
		logger.info("获取myOrder进行中订单，client="+clientOrderMode);
		//20200421扫码点餐页面同一在线与外卖、与桌码独立区分
		if(!Constants.clientOrderMode.SCAN_ORDER_MODE.getValue().equals(clientOrderMode)){
			//查询在线订单信息
//            waimaiParam.setOutSupportId(Long.parseLong(clientOrderMode.toString()));
            List<Integer> inOuterSupportIds = new LinkedList<>();
            inOuterSupportIds.add(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue());
            inOuterSupportIds.add(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue());
//            inOuterSupportIds.add(Constants.clientOrderMode.SCAN_ORDER_MODE.getValue());
            waimaiParam.setInOuterSupportIds(inOuterSupportIds);

			waimaiParam.setBuyerId(buyerId);
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
			waimaiParam.setIsHexiao(0);
			logger.info("获取进行中订单:"+waimaiParam.toString());
			waimai = waimaiServiceApi.getWaimaiAndDetailByBuyerId(waimaiParam);
			// 查询店铺配置白名单
			List<BusinessWhiteList> BusinessWhiteList = shopperInfoServiceApi.getShopperBusinessWhiteList(storeId, shopper.getParentId(), CommConstant.WHILET_SWEEP_REPEAT_JUMP_PAGE);
			if (!CollectionUtils.isEmpty(BusinessWhiteList) && Utils.isEmpty(waimai)) {
				waimaiParam.setIsHexiao(1);
				waimaiParam.setBuyerId(buyerId);
				waimaiParam.setOutSupportId(Long.valueOf(clientOrderMode));
				waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
				waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
				waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ELEVEN.getValue());
				waimai = waimaiServiceApi.getWaimaiAndDetailByBuyerId(waimaiParam);
				waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
			}
		}else{
		    logger.info("查询口碑订单");
			if(shopperConfig != null && new Integer(1).equals(shopperConfig.getKoubeiDinner())){
				//查询口碑正餐后付订单
				waimaiParam.setOutSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
			}else{
				//查询扫码下单订单
				if(shopperConfig != null && new Integer(1).equals(shopperConfig.getFirstPayMent()) && new Integer(1).equals(shopperConfig.getIsOpenDeskmateSinglePoint())){
					//查询口碑正餐后付订单
					waimaiParam.setBuyerId(buyerId);
				}
				waimaiParam.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
			}
			waimaiParam.getNotStatuses().add(Constants.orderStatus.STATUS_TWO.getValue());
			waimaiParam.getNotStatuses().add(Constants.orderStatus.STATUS_ELEVEN.getValue());
			waimaiParam.getNotStatuses().add(Constants.orderStatus.STATUS_TWELVE.getValue());
			if (StringUtils.isNotEmpty(tableName)) {
				//桌台不为空则订单为扫码下单
				waimaiParam.setTableNum(tableName);
				waimai = waimaiServiceApi.getWaimaiAndDetailByTableNum(waimaiParam);
			} else {
				//桌台不为空则订单为扫码下单
				waimaiParam.setBuyerId(buyerId);
				waimai = waimaiServiceApi.getWaimaiAndDetailByTableNum(waimaiParam);
			}
		}
		return waimai;
	}
	
	public WaimaiExtend getCreateWaimai(Integer storeId, String tableName, String buyerId,Integer clientOrderMode,Integer koubeiDinner) {
		WaimaiParam waimaiParam = new WaimaiParam();
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		waimaiParam.setStoreId(storeId);
		waimaiParam.setStartDate(startDate);
		waimaiParam.setEndDate(endDate);
		WaimaiExtend waimai=null;
		Object config = redisServiece.getObj(storeId+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if(config==null){
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			if(shopperConfig!=null){
				// map转成对象
				shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
			}
		}else{
			shopperConfigExt = (ShopperConfigExtend)config;
		}
		//查询订单信息
		if(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)){
			waimaiParam.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
//            List<Integer> inOuterSupportIds = new LinkedList<>();
//            inOuterSupportIds.add(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue());
//            inOuterSupportIds.add(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue());
//            waimaiParam.setInOuterSupportIds(inOuterSupportIds);
			waimaiParam.setBuyerId(buyerId);
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
			waimaiParam.setIsHexiao(0);
			waimai = waimaiServiceApi.getWaimaiAndDetailByBuyerId(waimaiParam);
		}else{
			//查询扫码下单订单（包含无桌台）
			if(new Integer(1).equals(koubeiDinner)){
				//口碑正餐后付订单
				waimaiParam.setOutSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
			}else{
				//扫码下单订单
				waimaiParam.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
			}
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
			waimaiParam.getStatuses().add(Constants.orderStatus.STATUS_THREE.getValue());
			waimaiParam.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
			if (StringUtils.isNotEmpty(tableName)) {
				//桌台不为空则订单为扫码下单
				waimaiParam.setTableNum(tableName);
				if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
					waimaiParam.setBuyerId(buyerId);
					waimai = waimaiServiceApi.getWaimaiAndDetailByTableNumAndBuyerId(waimaiParam);
				} else {
					waimai = waimaiServiceApi.getWaimaiAndDetailByTableNum(waimaiParam);
				}
			} else {
				//桌台不为空则订单为扫码下单
				waimaiParam.setBuyerId(buyerId);
				waimai = waimaiServiceApi.getWaimaiAndDetailByTableNum(waimaiParam);
			}
		}
		return waimai;
	}

	@Override
	public WaimaiExtend getWaimaiDeatilsByOrderNum(String orderNum) {

		return waimaiServiceApi.getWaimaiAndDetailByOrderNum(orderNum);
	}

	@Override
    public CoreResponse<HistoryOrderVO> getHistoryOrderDetail(Integer storeId, String buyerId, Integer pageCount, String createTime,Integer clientOrderMode) {
        String url=null;
        //餐获取店铺是否开启智能取柜
        Object config = redisServiece.getObj(storeId+"_shopperConfig");
        ShopperConfigExtend shopperConfigExt = null;
        if(config==null){
            Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
            if(shopperConfig!=null){
                // map转成对象
                shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
            }
        }else{
            shopperConfigExt = (ShopperConfigExtend)config;
        }
        CoreResponse<HistoryOrderVO> res = new CoreResponse<HistoryOrderVO>();
        HistoryOrderVO historyOrder = new HistoryOrderVO();
        WaimaiParam param = new WaimaiParam();

        param.setStoreId(storeId);
        param.setBuyerId(buyerId);
        param.setPageCount(pageCount);
        param.setStartDate(createTime);
        param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
        if(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)){
            param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
        } else if(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().equals(clientOrderMode)){
            param.setOutSupportId(Constants.orderOutSupportId.WAIMAI_ORDER.getValue());
        }else{
            //开启口碑正餐后付
            if(shopperConfigExt!=null && new Integer(1).equals(shopperConfigExt.getKoubeiDinner())){
                param.setOutSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
            }else{
                param.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
            }
        }
        //获取历史订单信息
        List<WaimaiExtend> waimaiList = waimaiServiceApi.getHistoryWaimaiList(param);
        if (CollectionUtils.isEmpty(waimaiList)) {
            res.setData(null);
            res.setMsg("暂无历史订单");
            return res;
        }
        List<WaimaiVO> waimaiVOList = new ArrayList<WaimaiVO>();
        List<CupboardOrderRecordVO> recordVOList= new ArrayList<CupboardOrderRecordVO>();
        Integer invoiceType=0;
        for (WaimaiExtend waimai : waimaiList) {
            WaimaiVO waimaiVO = new WaimaiVO();
            BeanUtils.copyProperties(waimai, waimaiVO);
            //取餐号不足四位补零
            if(waimai.getOrderSeq()!=null){
                waimaiVO.setOrderSeq(Utils.getOrderSeq(waimai.getOrderSeq()));
            }
            //如果为在线订单则可能存在取餐柜订单
            if(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)){
                //获取取餐柜订单的柜子状态信息
                CupboardOrderRecord orderRecord = new CupboardOrderRecord();
                orderRecord.setOrderNum(waimai.getOrderNum());
                List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
                if (!CollectionUtils.isEmpty(orderRecordList)) {
                    int statusTwo = 0;
                    int statusZero = 0;
                    // 餐柜个数
                    int orderSize = orderRecordList.size();
                    if (!new Integer(2).equals(waimaiVO.getPrepMealStatus())) {
                        for (CupboardOrderRecord record : orderRecordList) {
                            // 取餐柜订单中 多个餐柜中只要有一个为1待取餐则这个订单为待取餐
                            if (new Integer(1).equals(record.getGoodStatus())) {
                                waimaiVO.setPrepMealStatus(1);
                            }
                            // 餐柜的状态为2已取餐
                            if (new Integer(2).equals(record.getGoodStatus())) {
                                statusTwo++;
                            }
                            // 餐柜的状态为0制作中
                            if (new Integer(0).equals(record.getGoodStatus())) {
                                statusZero++;
                            }
                            CupboardOrderRecordVO orderRecordVO = new CupboardOrderRecordVO();
                            BeanUtils.copyProperties(record, orderRecordVO);
                            recordVOList.add(orderRecordVO);
                        }
                        // 全部都是状态为0的柜台
                        if (orderSize == statusZero) {
                            waimaiVO.setPrepMealStatus(0);
                            // 状态柜台为2的
                        } else if (statusTwo == orderSize || ((statusTwo + statusZero) == orderSize)) {
                            waimaiVO.setPrepMealStatus(2);
                        }
                    }
                    waimaiVO.setRecordList(recordVOList);
                    // 未查询到取餐柜柜子则默认为0
                }
            }
//            if(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().equals(waimai.getOuterSupportId())){
//                waimaiVO.setReceiverLng(waimai.getReceiverLng());
//                waimaiVO.setReceiverLat(waimai.getReceiverLat());
//                waimaiVO.setDeliveryPay(waimai.getDeliveryPay());
//                waimaiVO.setReceiverName(waimai.getReceiverName());
//                waimaiVO.setReceiverSex(waimai.getReceiverSex());
//                waimaiVO.setReceiverTel(waimai.getBuyerMobile());
//                waimaiVO.setReceiverAddress(waimai.getAddress());
//                waimaiVO.setBuyerNick(waimai.getBuyNick());
//                waimaiVO.setBagPrice(waimai.getOtherPrice());
//                waimaiVO.setStartDeliveryTime(waimai.getStartDeliveryTime());
//                waimaiVO.setEndDeliveryTime(waimai.getEndDeliveryTime());
//                waimaiVO.setReachTime(waimai.getReachTime());
//            }
            //订单创建时间及支付时间date转换String
            waimaiVO.setCreateTime(DateUtils.getDateChangeString(waimai.getCreateTime()));
            waimaiVO.setPayTime(DateUtils.getDateChangeString(waimai.getPayTime()));

            if(!CollectionUtils.isEmpty(waimai.getItems())){
                for(WaimaiItemExtend item:waimai.getItems()){
                    if(item!=null){
                        WaimaiItemVO itemVO = new WaimaiItemVO();
                        BeanUtils.copyProperties(item, itemVO);
                        itemVO.setPropName(item.getPropDesc());
                        waimaiVO.getWaimaiItems().add(itemVO);
                    }
                }
            }

            if(shopperConfigExt!=null && new Integer(1).equals(shopperConfigExt.getIsOpenKDS())&& Constants.orderOutSupportId.ONLINE_ORDER.getValue().equals(waimaiVO.getOuterSupportId())){
                //开通kds取餐柜订单，查询单个菜品的状态，及根据菜品状态判断订单状态
                waimaiVO = waimaiVOGoodsStatus(shopperConfigExt.getIsOpenKDS(),waimaiVO);
            }
            // 开通开具发票，只有已支付，且订单时间在两个月内的订单具有开票权限
            logger.info("发票shopperConfigExt.getIsOpenInvoice()"+shopperConfigExt.getIsOpenInvoice());
            if(shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getIsOpenInvoice())  && new Integer(1).equals(waimaiVO.getPayStatus())){
                List<InvoiceServiceInfo> InvoiceServiceInfo = shopperInfoServiceApi.findInvoiceServiceInfo(storeId);
                waimaiVO = waimaiVOInvoice(shopperConfigExt.getIsOpenInvoice(), waimaiVO, new Date(), storeId, InvoiceServiceInfo);
            }
            if (waimaiVO.getIsOpenInvoice()==true){
                //查询开通那种发票  百望：1,null  诺诺：2
                invoiceType= shopperInfoServiceApi.findInvoiceType(storeId);
            }

            //发票
            if (new Integer(2).equals(invoiceType)){
                Map<String, String> map=new HashMap<>();
                map.put("storeId",storeId.toString());
                map.put("orderNum", waimaiVO.getOrderNum());
                map.put("totalPrice",waimaiVO.getTotalPrice().toString());
                map.put("invoiceType",1+"");
                map.put("invoiceServerType",2+"");
                CoreResponse<String> result = HttpUtils.doGet(invoiceServiceUrl, map, 60000, 60000, "UTF-8");
                logger.info("诺诺调用接口返回result:"+JSONObject.toJSONString(result));
                if (!Utils.isEmpty(result) && !Utils.isEmpty(result.getData()) ){
                    //logger.info("result.getData():"+result.getData());
                    JSONObject json = JSONObject.parseObject(result.getData());
                    //logger.info("json:"+json.getBoolean("success")+"code:"+json.getString("code")+"data"+json.get("data"));
                    if (json.getBoolean("success") && ("10000").equals(json.getString("code"))){
                        //诺诺地址
                        url=json.get("data").toString();
                    }
                }
            }
            //百望地址
            if (new Integer(1).equals(invoiceType)|| Utils.isEmpty(invoiceType)){
                url=invoiceUrl+"/ajax/toOpenInvoice.htm?storeId=" + storeId + "&orderNum="+ waimaiVO.getOrderNum() + "&totalPrice=" + waimaiVO.getTotalPrice();
            }
            waimaiVO.setInvoiceUrl(url);
            //20200519 waimai页面需要单品原价+加料价格
            List<WaimaiItemVO> waimaiItems = waimaiVO.getWaimaiItems();
            boolean isMemberPrice = false;
            double memberTotalPrice = 0D;
            if(waimaiItems != null){
                for (WaimaiItemVO item :waimaiItems) {
                    //20200519 页面需求单品原价+加料加个
                    if(!new Integer(1).equals(item.getIsPackage()) && !new Integer(1).equals(item.getIsPackage())){
                        double propPrice = item.getPropPrice() == null ? 0D : item.getPropPrice();
                        double originalPrice = item.getOriginalPrice() == null ? 0D : item.getOriginalPrice();
                        item.setOriginalPrice(com.silverbox.core.util.Arith.add(propPrice,originalPrice));
                    }
                    //会员价20200603回显
                    if(!Utils.isEmpty(item.getMemberPrice())){
                        memberTotalPrice = Arith.add(memberTotalPrice,Arith.mul(item.getBuyCount(),item.getMemberPrice()));
                        isMemberPrice = true;
                    }
                }
            }
            if(isMemberPrice){
                waimaiVO.setTotalPrice(memberTotalPrice);
            }
            waimaiVOList.add(waimaiVO);
        }
        Waimai waimai = getMyOrderStatus(storeId, null, buyerId, clientOrderMode);
        boolean flag = false;
        if(waimai!=null){
            flag = true;
        }
        historyOrder.setOrderList(waimaiVOList);
        historyOrder.setFlag(flag);
        res.setData(historyOrder);
        res.setMsg("查询成功");
        return res;
    }

	@Override
	public Waimai getWaimaiOrderByOrderNum(String orderNum) {
		return waimaiServiceApi.getWaimaiByOrderNum(orderNum);
	}

	@Override
	public List<Integer> getGoodsCoupon(ThirdUserInfo thirdUserInfo, /* ShopperVo shopper */Integer storeId,
			Set<Integer> goodIds, String shopId) {
		String nowDate = DateUtils.getNowTime();
		List<DiscountInfo> listDiscount = shopperGoodsServiceApi.getDiscountGoods(shopId, null, nowDate, null);
		if (CollectionUtils.isEmpty(listDiscount)) {
			return null;
		}
		StringBuffer disItemIds = new StringBuffer("");
		StringBuffer disItemTypes = new StringBuffer("");
		List<Integer> goodList = new ArrayList<Integer>();
		for (DiscountInfo discount : listDiscount) {
			if (goodIds.contains(discount.getGoodsId())) {
				goodList.add(discount.getGoodsId());
				if (StringUtils.isNotEmpty(discount.getItemId().toString())) {
					disItemIds.append(discount.getItemId().toString() + ",");
					disItemTypes.append(discount.getItemType() + ",");
				}
			}
		}
		if (listDiscount.size() > 0 && StringUtils.isNotEmpty(disItemIds.toString()) && ",".equals(
				disItemIds.toString().substring(disItemIds.toString().length() - 1, disItemIds.toString().length()))) {
			disItemIds.deleteCharAt(disItemIds.toString().length() - 1);
			disItemTypes.deleteCharAt(disItemTypes.toString().length() - 1);
		}
		if (StringUtils.isNotEmpty(disItemIds.toString()) && StringUtils.isNotEmpty(disItemTypes.toString())
			 && StringUtils.isNotEmpty(thirdUserInfo.getThirdUserId()) && StringUtils.isNotEmpty(thirdUserInfo.getUserId())) {

			String userId = thirdUserInfo.getThirdUserId().length() > thirdUserInfo.getUserId().length()
					? thirdUserInfo.getUserId()
					: thirdUserInfo.getThirdUserId();
			receiveCoupon(/* shopper.getId() */storeId, userId, disItemIds.toString(), disItemTypes.toString(),
					couponUrl);
		}
		return goodList;
	}

	@Override
	public int updateWaimai(Waimai waimai) {
		return waimaiServiceApi.updateWaimai(waimai);
	}

	@Override
	public List<WaimaiSerialnumber> getWaimaiSerialnumberByOrderNum(String orderNum) {
		return waimaiServiceApi.getWaimaiSerialnumberByOrderNum(orderNum);
	}

	@Override
	public int saveWaimaiSerialnumber(WaimaiSerialnumber record) {
		return waimaiServiceApi.saveWaimaiSerialnumber(record);
	}

	@Override
	public int deleteWaimaiSerialNumberByOutTradeNo(String outTradeNo) {
		return waimaiServiceApi.deleteWaimaiSerialNumberByOutTradeNo(outTradeNo);
	}

	@Override
	public UndiscountWaimaiDTO getUndiscountWaimaiDTO(WaimaiExtend waimai) {
		UndiscountWaimaiDTO waimaiDTO = new UndiscountWaimaiDTO();
		waimaiDTO.setOrderNum(waimai.getOrderNum());
		waimaiDTO.setOuterSupportId(waimai.getOuterSupportId());
		List<UnDiscountWaimaiItemDTO> itemDTOList = new ArrayList<UnDiscountWaimaiItemDTO>();
		for (WaimaiItem item : waimai.getItems()) {
			UnDiscountWaimaiItemDTO itemDTO = new UnDiscountWaimaiItemDTO();
			itemDTO.setBuyCount(item.getBuyCount());
			itemDTO.setBuyPrice(item.getBuyPrice());
			itemDTO.setCategoryName(item.getCategoryName());
			itemDTO.setGive(item.getGive());
			itemDTO.setGoodsId(item.getGoodsId());
			itemDTO.setGoodsName(item.getGoodsName());
			itemDTO.setId(item.getId());
			itemDTO.setIsRefund(item.getIsRefund());
			itemDTO.setOriginalPrice(item.getOriginalPrice());
			itemDTO.setOutGoodsId(item.getOutGoodsId());
			itemDTO.setRefundCount(item.getRefundCount());
			itemDTO.setType(item.getTypeName());
			itemDTOList.add(itemDTO);
		}
		waimaiDTO.setItems(itemDTOList);
		return waimaiDTO;
	}

	@Override
	public CoreResponse<KoubeiDiscountInfoVO> getKoubeiDiscountInfo(KoubeiDiscountEntryVO koubeiDiscount) {
		WaimaiExtend waimai = getWaimaiDeatilsByOrderNum(koubeiDiscount.getOrderNum());
		CoreResponse<KoubeiDiscountInfoVO> res = new CoreResponse<KoubeiDiscountInfoVO>();
		if (null == waimai || Utils.isEmpty(waimai.getItems())) {
			res.setMsg("订单不存在!");
			// res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setStatusInfo(StatusInfo.SUCCESS);
			return res;
		}
		if(StringUtils.isEmpty(koubeiDiscount.getAliPayUserId())){
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setSubMsg("查询成功！口碑门店ID为空");
			return res;
		}
		AlipayApplyAuthToken token = new AlipayApplyAuthToken();
		token.setAlipayUserId(koubeiDiscount.getAliPayUserId());
		token.setAppId(sweepOrderAppId);
		List<AlipayApplyAuthToken> list = alipayServiceApi.getAlipayApplyAuthToken(token);
		token = Utils.isEmpty(list)?null:list.get(0);
		if (null == token) {
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setSubMsg("获取token信息失败");
			return res;
		}
		AlipayClient alipayClient = AlipayUtils.initAlipayClientByAppId(AlipayServiceEnvConstants.PRIVATE_KEY.getValue(),
				AlipayServiceEnvConstants.ALIPAY_PUBLIC_KEY.getValue(), sweepOrderAppId);
		KoubeiTradeOrderConsultRequest request = new KoubeiTradeOrderConsultRequest();
		UndiscountWaimaiDTO waimaiDTO = getUndiscountWaimaiDTO(waimai);
		Map<String, Object> unDiscountAmountMap = alipayServiceApi.getUnDiscountAmount(koubeiDiscount.getStoreId(), Long.valueOf(5),
				waimaiDTO, false);
		Double unDiscountAmount = 0.0;
		Double itemTotalAmount = 0.0;
		Double totalAmount = waimai.getTotalPrice();
		unDiscountAmount = Double.parseDouble(unDiscountAmountMap.get("unDiscountAmount").toString());
		itemTotalAmount = Double.parseDouble(unDiscountAmountMap.get("totalAmount").toString());
		if (Arith.sub(itemTotalAmount, totalAmount) != 0d) {
			logger.info("订单编号为" + waimai.getOrderNum() + "  订单明细总金额和订单总金额没有对上,没有优惠前置咨询!");
			 res.setStatusInfo(StatusInfo.SUCCESS);
			// res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setSubMsg("订单明细总金额和订单总金额没有对上!");
			return res;
		}
		JSONObject json = new JSONObject();
		json.fluentPut("user_id", koubeiDiscount.getBuyerId()).fluentPut("total_amount", totalAmount + "");
		if (unDiscountAmount > totalAmount) {
			unDiscountAmount = totalAmount;
		}
		if (unDiscountAmount > 0) {
			json.put("undiscountable_amount", unDiscountAmount + "");
		}
		json.put("shop_id", waimai.getKoubeiShopid());
		if (!Utils.isEmpty(koubeiDiscount.getApdid_token())) {
			json.put("apdid_token", koubeiDiscount.getApdid_token());
		}
		json.put("request_id", System.currentTimeMillis() + "");
		String details = unDiscountAmountMap.get("details").toString();
		json.put("goods_info", JSONObject.parse(details));
		json = JSONObject.parseObject(json.toJSONString());
		request.setBizContent(json.toJSONString());
		request.putOtherTextParam("app_auth_token", token.getAuthToken());

		Double payRealMoney = 0.0d;
		List<DiscountDetail> hitDisCountDetailList = new ArrayList<DiscountDetail>();
		List<DiscountDetail> unHitDisCountDetailList = new ArrayList<DiscountDetail>();
		KoubeiTradeOrderConsultResponse response = null;
		try {
			response = alipayClient.execute(request);
			// 令牌失效，重新刷新token
			if (null == response || !response.isSuccess()) {
				List<AlipayApplyAuthToken> tokens = alipayServiceApi.getAlipayApplyAuthToken(token);
				token = Utils.isEmpty(tokens)?null:tokens.get(0);
				token = flushAuthToken(token);
				if (token != null) {
					request.putOtherTextParam("app_auth_token", token.getAuthToken());
					// 再次执行
					response = alipayClient.execute(request);
				}
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setSubMsg("调用支付宝领券失败");
			return res;
		}
		// logger.info("优惠前置领券==================response"+JSONObject.toJSONString(response));
		if (null != response && response.isSuccess()) {
			payRealMoney = Double.parseDouble(response.getBuyerPayAmount());
			List<DiscountDetail> disCountDetailList = response.getDiscountDetail();
			if (disCountDetailList != null && disCountDetailList.size() > 0) {
				for (DiscountDetail temp : disCountDetailList) {
					if (temp.getIsHit().equals("true")) {
						hitDisCountDetailList.add(temp);
					} else {
						unHitDisCountDetailList.add(temp);
					}
				}
			}
		} else {
			// res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setSubMsg("领取优惠券失败");
			return res;
		}
		KoubeiDiscountInfoVO koubeiDiscountVO = new KoubeiDiscountInfoVO();
		koubeiDiscountVO.setHitDisCountDetailList(hitDisCountDetailList);
		koubeiDiscountVO.setUnHitDisCountDetailList(unHitDisCountDetailList);
		koubeiDiscountVO.setPayRealMoney(payRealMoney);
		res.setData(koubeiDiscountVO);
		res.setStatusInfo(StatusInfo.SUCCESS);
		res.setSubMsg("查询成功");
		return res;
	}

	@Override
	public CoreResponse<WaimaiVO> getWaimaiByOrderNum(OrderQueryDto orderQueryVo) {
        String orderNum = orderQueryVo.getOrderNum();
        CoreResponse<WaimaiVO> res = new CoreResponse<WaimaiVO>();
		WaimaiVO waimaiVO = new WaimaiVO();
		//获取订单信息
		WaimaiExtend waimai = waimaiServiceApi.getWaimaiAndDetailByOrderNum(orderNum);
		if (waimai == null) {
			res.setMsg("暂无订单信息");
			res.setData(null);
			return res;
		}
		BeanUtils.copyProperties(waimai, waimaiVO);
		//取餐号不足四位补零
		if(waimai.getOrderSeq()!=null){
			waimaiVO.setOrderSeq(Utils.getOrderSeq(waimai.getOrderSeq()));
		}
		//获取取餐柜的柜子信息
		CupboardOrderRecord orderRecord = new CupboardOrderRecord();
		if(waimai!=null && !StringUtils.isEmpty(waimai.getTakeMealCode()) && waimai.getTakeMealCode().length()>=17){
			orderRecord.setTakeCode(waimai.getTakeMealCode());
			orderRecord.setStoreId(waimai.getShopId());
		}else{
			orderRecord.setOrderNum(orderNum);
		}
		List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
		if(!CollectionUtils.isEmpty(orderRecordList)){
			List<CupboardOrderRecordVO> recordVOList= new ArrayList<CupboardOrderRecordVO>();
			int statusTwo = 0;
			int statusZero = 0;
			//餐柜个数
			int orderSize = orderRecordList.size();
			for(CupboardOrderRecord record:orderRecordList){
				// 取餐柜订单中 多个餐柜中只要有一个为1待取餐则这个订单为待取餐
				if (!new Integer(2).equals(waimaiVO.getPrepMealStatus())
						&& new Integer(1).equals(record.getGoodStatus())) {
					waimaiVO.setPrepMealStatus(1);
				}
				//餐柜的状态为2已取餐
				if(new Integer(2).equals(record.getGoodStatus())){
					statusTwo++;
				}
				//餐柜的状态为0制作中
				if(new Integer(0).equals(record.getGoodStatus())){
					statusZero++;
				}
				
				CupboardOrderRecordVO orderRecordVO = new CupboardOrderRecordVO();
				BeanUtils.copyProperties(record, orderRecordVO);
				recordVOList.add(orderRecordVO);
			}
			//如果取餐柜订单已经
			if(!new Integer(2).equals(waimaiVO.getPrepMealStatus())){
				//全部都是状态为0的柜台
				if(orderSize==statusZero){
					waimaiVO.setPrepMealStatus(0);
					//状态柜台为2的
				}else if(statusTwo==orderSize ||((statusTwo+statusZero)==orderSize)){
					waimaiVO.setPrepMealStatus(2);
				}
			}
			waimaiVO.setRecordList(recordVOList);
		}else{
			waimaiVO.setPrepMealStatus(0);
		}
		//订单创建时间及支付时间date转换String
		waimaiVO.setCreateTime(DateUtils.getDateChangeString(waimai.getCreateTime()));
		waimaiVO.setPayTime(DateUtils.getDateChangeString(waimai.getPayTime()));
		//set用户信息
		WaimaiUserInfoVO userInfo = new WaimaiUserInfoVO();
		userInfo.setBuyerId(waimai.getBuyerId());
		userInfo.setNickName(StringUtils.isEmpty(waimai.getBuyNick())?"吃货":waimai.getBuyNick());
		userInfo.setBuyerPhone(waimai.getBuyerPhone());
		waimaiVO.setUserInfo(userInfo);

		//set外卖信息
        waimaiVO.setPurchStatus(waimai.getPurchStatus());
        waimaiVO.setDeliveryStatus(waimai.getDeliveryStatus());
        waimaiVO.setReceiverLng(waimai.getReceiverLng());
        waimaiVO.setReceiverLat(waimai.getReceiverLat());
        waimaiVO.setDeliveryPay(waimai.getDeliveryPay());
        waimaiVO.setReceiverName(waimai.getReceiverName());
        waimaiVO.setReceiverSex(waimai.getReceiverSex());
        waimaiVO.setReceiverTel(waimai.getBuyerMobile());
        waimaiVO.setReceiverAddress(waimai.getAddress());
        waimaiVO.setBuyerNick(waimai.getBuyNick());
        waimaiVO.setBagPrice(waimai.getOtherPrice());
        waimaiVO.setStartDeliveryTime(waimai.getStartDeliveryTime());
        waimaiVO.setEndDeliveryTime(waimai.getEndDeliveryTime());
        waimaiVO.setReachTime(waimai.getReachTime());

		//set店铺信息
		WaimaiShopperVO shopperInfo = new WaimaiShopperVO();
		shopperInfo.setStoreId(waimai.getShopId());
		shopperInfo.setShopperId(waimai.getShopperId());
		shopperInfo.setShopName(waimai.getShopName());
		shopperInfo.setShopperName(waimai.getShopperName());
		shopperInfo.setShopAddress(waimai.getShopAddress());
		shopperInfo.setShopLogo(waimai.getShopLogo());
		shopperInfo.setKoubeiShopid(waimai.getKoubeiShopid());
		waimaiVO.setShopperInfo(shopperInfo);

        //20200708 优惠券信息临时存储
        String extendParams = waimai.getExtendParams();
        if(!Utils.isEmpty(extendParams)){
            JSONObject couponsUsedJson = JSONObject.parseObject(extendParams);
            if(couponsUsedJson.containsKey("uuidArray")){
                waimaiVO.setCouponsUsedId(couponsUsedJson.toJSONString());
            }
        }

        waimaiVO.setTotalPrice(waimai.getTotalPrice());
        waimaiVO.setMemberTotalPrice(waimai.getTotalPrice());

        double totalBuyOriginalPrice = 0D;
        double buyOriginalPrice = 0D;
        if(!CollectionUtils.isEmpty(waimai.getItems())){
            for(WaimaiItemExtend item:waimai.getItems()){
                WaimaiItemVO itemVO = new WaimaiItemVO();
                BeanUtils.copyProperties(item, itemVO);
                itemVO.setPropName(item.getPropDesc());
                waimaiVO.getWaimaiItems().add(itemVO);

                buyOriginalPrice = !Utils.isEmpty(item.getMemberPrice()) && !Utils.isEmpty(orderQueryVo.getMemberId()) ? item.getMemberPrice() : (Utils.isEmpty(item.getCouponCode()) ? item.getOriginalPrice() : item.getBuyPrice());
                totalBuyOriginalPrice = Arith.add(totalBuyOriginalPrice,Arith.mul(item.getBuyCount(),buyOriginalPrice));
            }
        }
        waimaiVO.setTotalBuyOriginalPrice(totalBuyOriginalPrice);

        //获取店铺是否开启智能取餐柜
		Object config = redisServiece.getObj(waimai.getShopId()+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if(config==null){
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(waimai.getShopId());
			if(shopperConfig!=null){
				// map转成对象
				shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
			}
		}else{
			shopperConfigExt = (ShopperConfigExtend)config;
		}
		// 开通kds取餐柜订单，查询单个菜品的状态，及根据菜品状态判断订单状态
		if (Constants.orderOutSupportId.ONLINE_ORDER.getValue().equals(waimai.getOuterSupportId())
				&& new Integer(1).equals(shopperConfigExt.getIsOpenKDS())) {
			waimaiVO = waimaiVOGoodsStatus(shopperConfigExt.getIsOpenKDS(),waimaiVO);
		}

		waimaiVO.setIsOpenWxPay(1);

        // 先查询子店铺是否开通微信扫呗
		/*boolean store_saobei = shopperInfoServiceApi.isSaoBei(waimai.getShopId(),null);
		if(store_saobei){
			waimaiVO.setIsOpenWxPay(1);
		}else{
			// 子店铺没有再查询主店铺是否开通微信扫呗
			boolean shopper_saobei = shopperInfoServiceApi.isSaoBei(null,waimai.getShopperId());
			if(shopper_saobei){
				waimaiVO.setIsOpenWxPay(1);
			}else{
				// 先查询子店铺是否开通蚂蚁微信
				boolean storeWxPay = shopperInfoServiceApi.isWxPay(waimai.getShopId(), null);
				if (storeWxPay) {
					waimaiVO.setIsOpenWxPay(1);
				} else {
					// 子店铺没有再查询主店铺是否开通蚂蚁微信
					boolean shopWxPay = shopperInfoServiceApi.isWxPay(null, waimai.getShopperId());
					waimaiVO.setIsOpenWxPay(shopWxPay ? 1 : 0);
				}
			}
	    }*/
		res.setData(waimaiVO);
		return res;
	}

	@Override
	public Waimai hasUnfinishedOrder(Integer storeId, String tableName,Integer md) {
		WaimaiParam param = new WaimaiParam();
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		//获取redis店铺配置信息
		Object config = redisServiece.getObj(storeId+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		param.setStoreId(storeId);
		param.setTableNum(tableName);
		//口碑正餐后付
		if(shopperConfigExt!=null && new Integer(1).equals(shopperConfigExt.getKoubeiDinner())){
			param.setOutSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
		}else{
			//扫码下单
			param.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
		}
		param.getNotStatuses().add(Constants.orderStatus.STATUS_TWO.getValue());
		param.getNotStatuses().add(Constants.orderStatus.STATUS_TWELVE.getValue());
        param.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
		param.setStartDate(startDate);
		param.setEndDate(endDate);
		logger.info("VUE扫码下单查询进行中订单,md值为："+md);
		if(new Integer(4).equals(md)){//外卖
            //20200318 外卖拣货先支付后取货为进行中订单 取消未支付查询
            param.setPayStatus(null);
            param.setNotStatuses(null);
            param.setOutSupportId(81L);
            param.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
            param.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
            param.getStatuses().add(Constants.orderStatus.STATUS_MINUSONE.getValue());
        }
        logger.info("VUE扫码下单查询进行中订单,参数："+param.toString());
		Waimai waimai = waimaiServiceApi.getUnfinishWaimaiByTableNum(param);
		return waimai;
	}

	@Override
	public CoreResponse<StatusInfo> deleteHistoryOrderByOrderId(String[] orderIds) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		if (orderIds != null && orderIds.length > 0) {
			List<String> orderList = Arrays.asList(orderIds);
			waimaiServiceApi.deleteOrderByIds(orderList);
		} else {
			res.setStatusInfo(StatusInfo.ERROR_40002);
			res.setMsg("参数异常");
		}
		return res;
	}

	@Override
	public CoreResponse<WaimaiVO> getMyOrder(OrderQueryDto orderQueryVo) {

		CoreResponse<WaimaiVO> res = new CoreResponse<WaimaiVO>();
        Integer storeId = orderQueryVo.getStoreId();
        String buyerId = orderQueryVo.getBuyerId();
        Integer clientOrderMode = orderQueryVo.getClientOrderMode();
        String tableName = orderQueryVo.getTableName();
        String wisdomFlag = orderQueryVo.getWisdomFlag();
        String takeMealCode = orderQueryVo.getTakeMealCode();

        WaimaiVO waimaiVO = new WaimaiVO();
		
		//获取店铺是否开启智能取餐柜
		Object config = redisServiece.getObj(storeId+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if(config==null){
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			if(shopperConfig!=null){
				// map转成对象
				shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
			}
		}else{
			shopperConfigExt = (ShopperConfigExtend)config;
		}
		
		WaimaiExtend waimai = null;
		//取餐柜的柜子信息
		List<CupboardOrderRecordVO> orderRecordVOList = new ArrayList<CupboardOrderRecordVO>();
		//根据取餐码获取24小时内订单信息
		if (!StringUtils.isEmpty(takeMealCode) && takeMealCode.length() >= 17
				&& Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)) {
			WaimaiParam param = new WaimaiParam();
			param.setStoreId(storeId);
			param.setTakeMealCode(takeMealCode);
			param.setStartDate(DateUtils.getBeforeDate(24));
			param.setEndDate(DateUtils.getNowTime());
			param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
			waimai = waimaiServiceApi.getwaimaiBytakeMealCode(param);
			CupboardOrderRecord orderRecord = new CupboardOrderRecord();
			orderRecord.setTakeCode(takeMealCode);
			orderRecord.setStoreId(storeId);
			//查询柜子状态
			List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);

			if(waimai!=null){
				if(!CollectionUtils.isEmpty(orderRecordList)){
					//根据柜子状态判断订单状态
					installOrderRecord(waimai,orderRecordList,orderRecordVOList);
				}else{
					waimai.setPrepMealStatus(0);
				}
			}else{
				if(!StringUtils.isEmpty(wisdomFlag) && !StringUtils.isEmpty(takeMealCode) && takeMealCode.length()>=17 && waimai==null && !CollectionUtils.isEmpty(orderRecordList)){
					waimai = new WaimaiExtend();
					installOrderRecord(waimai,orderRecordList,orderRecordVOList);
					BeanUtils.copyProperties(waimai, waimaiVO);
					waimaiVO.setRecordList(orderRecordVOList);
					res.setData(waimaiVO);
					return res;
				}
			}
		} else{
			//获取在线订单进行中订单信息
			waimai = getWaimaiDeatils(storeId, tableName, buyerId, clientOrderMode, shopperConfigExt);
			//如果店铺开启智能取餐柜则查询取餐柜订单
			if (new Integer(1).equals(shopperConfigExt.getIntelligenceCabinet())
					&& (Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue()).equals(clientOrderMode)) {
				WaimaiParam param = new WaimaiParam();
				param.setStoreId(storeId);
				param.setBuyerId(buyerId);
				param.setOrderType(2);
				param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
				param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
				param.setStartDate(DateUtils.getBeforeDate(24));
				param.setEndDate(DateUtils.getNowTime());
				//获取在线订单取餐柜订单
				List<WaimaiExtend> waimaiList = waimaiServiceApi.getOnlineMealOrder(param);
				if(waimai==null && !CollectionUtils.isEmpty(waimaiList) && waimaiList.get(0)!=null){
					waimai = waimaiList.get(0);
				}
				if(waimai!=null ){
					CupboardOrderRecord orderRecord = new CupboardOrderRecord();
					orderRecord.setOrderNum(waimai.getOrderNum());
					List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
					if(!CollectionUtils.isEmpty(orderRecordList)){
						//根据柜子状态判断订单状态
						installOrderRecord(waimai,orderRecordList,orderRecordVOList);
					}else{
						waimai.setPrepMealStatus(0);
					}
				}
			}
		}
		if (waimai == null) {
			res.setMsg("暂无订单信息");
			res.setData(null);
			return res;
		}
		logger.info("在线订单进行中订单获取取餐柜信息2===========orderRecordVOList="+JSONObject.toJSONString(orderRecordVOList));
		BeanUtils.copyProperties(waimai, waimaiVO);
		
		if(waimai.getOrderSeq()!=null){
			waimaiVO.setOrderSeq(Utils.getOrderSeq(waimai.getOrderSeq()));
		}
        waimaiVO.setReceiverAddress(waimai.getAddress());
		waimaiVO.setRecordList(orderRecordVOList);
		//订单创建时间及支付时间date转换String
		waimaiVO.setCreateTime(DateUtils.getDateChangeString(waimai.getCreateTime()));
		waimaiVO.setPayTime(DateUtils.getDateChangeString(waimai.getPayTime()));
		//set用户信息
		WaimaiUserInfoVO userInfo = new WaimaiUserInfoVO();
		userInfo.setBuyerId(waimai.getBuyerId());
		userInfo.setNickName(StringUtils.isEmpty(waimai.getBuyNick())?"吃货":waimai.getBuyNick());
        userInfo.setBuyerPhone(waimai.getBuyerMobile());
		waimaiVO.setUserInfo(userInfo);
		//20200519 waimai页面需要单品原价+加料价格
//        List<WaimaiItemVO> waimaiItems = waimaiVO.getWaimaiItems();
        List<WaimaiItemExtend> waimaiItems = waimai.getItems();
        double totalBuyOriginalPrice = 0D;
        double buyOriginalPrice;
        if(waimaiItems != null){
            for (WaimaiItemExtend item :waimaiItems) {
                //20200519 页面需求单品原价+加料加个
                if(!new Integer(1).equals(item.getIsPackage()) && !new Integer(2).equals(item.getIsPackage())){
                    double propPrice = item.getPropPrice() == null ? 0D : item.getPropPrice();
                    double originalPrice = item.getOriginalPrice() == null ? 0D : item.getOriginalPrice();
                    item.setOriginalPrice(com.silverbox.core.util.Arith.add(propPrice,originalPrice));
                }
                buyOriginalPrice = !Utils.isEmpty(item.getMemberPrice()) && !Utils.isEmpty(orderQueryVo.getMemberId()) ? item.getMemberPrice() : (Utils.isEmpty(item.getCouponCode()) ? item.getOriginalPrice() : item.getBuyPrice());
                totalBuyOriginalPrice = Arith.add(totalBuyOriginalPrice,Arith.mul(item.getBuyCount(),buyOriginalPrice));
                logger.info("item.getMemberPrice = "+ item.getMemberPrice() + ",item.getCouponCode = " +item.getCouponCode() + ",item.getBuyPrice() = " +item.getBuyPrice() );
                logger.info("totalBuyOriginalPrice = "+totalBuyOriginalPrice + ",buyOriginalPrice = " +buyOriginalPrice);
            }
        }

        //set店铺信息
		WaimaiShopperVO shopperInfo = new WaimaiShopperVO();
		shopperInfo.setStoreId(waimai.getShopId());
		shopperInfo.setShopperId(waimai.getShopperId());
		shopperInfo.setShopName(waimai.getShopName());
		shopperInfo.setShopperName(waimai.getShopperName());
		shopperInfo.setShopAddress(waimai.getShopAddress());
		shopperInfo.setShopLogo(waimai.getShopLogo());
		shopperInfo.setKoubeiShopid(waimai.getKoubeiShopid());
		waimaiVO.setShopperInfo(shopperInfo);
        if(!CollectionUtils.isEmpty(waimai.getItems())){
            logger.info("waimai.getItems()："+JSONObject.toJSONString(waimai.getItems()));
            for(WaimaiItemExtend item:waimai.getItems()){
                if(item!=null){
                    WaimaiItemVO itemVO = new WaimaiItemVO();
                    BeanUtils.copyProperties(item, itemVO);
                    itemVO.setPropName(item.getPropDesc());
                    waimaiVO.getWaimaiItems().add(itemVO);
                }
            }
        }
        waimaiVO.setTotalPrice(waimai.getTotalPrice());
        waimaiVO.setMemberTotalPrice(waimai.getTotalPrice());
        waimaiVO.setTotalBuyOriginalPrice(totalBuyOriginalPrice);
        //20200708 优惠券信息临时存储
        String extendParams = waimai.getExtendParams();
        if(!Utils.isEmpty(extendParams)){
            JSONObject couponsUsedJson = JSONObject.parseObject(extendParams);
            if(couponsUsedJson.containsKey("uuidArray")){
                waimaiVO.setCouponsUsedId(couponsUsedJson.toJSONString());
            }
        }

        // 开通kds取餐柜订单，查询单个菜品的状态，及根据菜品状态判断订单状态
		if (Constants.orderOutSupportId.ONLINE_ORDER.getValue().equals(waimai.getOuterSupportId())
				&& new Integer(1).equals(shopperConfigExt.getIsOpenKDS())) {
			waimaiVO = waimaiVOGoodsStatus(shopperConfigExt.getIsOpenKDS(), waimaiVO);
		}
		// 预发布默认开通微信支付
		waimaiVO.setIsOpenWxPay(1);
		// 先查询子店铺是否开通微信扫呗
		/*boolean store_saobei = shopperInfoServiceApi.isSaoBei(storeId,null);
		if(store_saobei){
			waimaiVO.setIsOpenWxPay(1);
		}else{
			// 子店铺没有再查询主店铺是否开通微信扫呗
			boolean shopper_saobei = shopperInfoServiceApi.isSaoBei(null,waimai.getShopperId());
			if(shopper_saobei){
				waimaiVO.setIsOpenWxPay(1);
			}else{
				// 先查询子店铺是否开通蚂蚁微信
				boolean storeWxPay = shopperInfoServiceApi.isWxPay(storeId,null);
				if (storeWxPay) {
					waimaiVO.setIsOpenWxPay(1);
				} else {
					// 子店铺没有再查询主店铺是否开通蚂蚁微信
					boolean shopWxPay = shopperInfoServiceApi.isWxPay(storeId, waimai.getShopperId());
					waimaiVO.setIsOpenWxPay(shopWxPay ? 1 : 0);
				}
			}
	    }*/
		res.setData(waimaiVO);
		return res;
	}
	
	/**
	 * 开通kds，获取菜品的取餐柜订单状态、根据菜品状态判断订单状态
	 * @param isOpenKDS
	 * @param waimaiVO
	 */
	public WaimaiVO waimaiVOGoodsStatus(Integer isOpenKDS, WaimaiVO waimaiVO) {
		// 是否开通KDS，开通KDS要判断单个菜品的状态 同时根据菜品状态判断订单状态
		if (new Integer(1).equals(isOpenKDS)
				&& Constants.orderOutSupportId.ONLINE_ORDER.getValue().equals(waimaiVO.getOuterSupportId())
				&& waimaiVO.getWaimaiItems().size() > 0) {
			int status = 0;
			int zeroStatus = 0;
			int oneStatus = 0;
			int twoStatus = 0;
			int threeStatus = 0;
			int systemCount = 0;
			for (WaimaiItemVO itemVO : waimaiVO.getWaimaiItems()) {
				boolean zeroFlag = false;
				boolean flag = false;
				//过滤餐具费、打包费、服务费
				if (CommConstant.SYSTEM_BAG_GOODS.equals(itemVO.getGoodsDesc()) || CommConstant.SYSTEM_BOX_GOODS
						.equals(itemVO.getGoodsDesc()) || CommConstant.SYSTEM_FWF_GOODS.equals(itemVO.getGoodsDesc())) {
					systemCount++;
					continue;
				}else{
					List<CupboardOrderRecord> orderRecordList = null;
					if(itemVO.getItemId()!=null){
						// 获取单个菜品取餐柜柜子状态
						orderRecordList = orderServiceApi.getCupboardGoodsStatus(waimaiVO.getOrderNum(),
								itemVO.getItemId(),	CalendarUtil.formatDateByString(DateUtils.getBeforeDate(24)));
					}else{
						// 获取单个菜品取餐柜柜子状态
						orderRecordList = orderServiceApi.getCupboardGoodsStatus(waimaiVO.getOrderNum(),
								itemVO.getId(),CalendarUtil.formatDateByString(DateUtils.getBeforeDate(24)));
					}
					List<CupboardOrderRecordVO> recordList = new ArrayList<CupboardOrderRecordVO>();
					int count = 0;
					if (!CollectionUtils.isEmpty(orderRecordList)) {
						for (CupboardOrderRecord record : orderRecordList) {
							if (new Integer(2).equals(record.getGoodStatus())) {
								count++;
							}
							CupboardOrderRecordVO recordVO = new CupboardOrderRecordVO();
							BeanUtils.copyProperties(record, recordVO);
							recordList.add(recordVO);
						}
						// 获取订单单个菜品取餐柜状态
						itemVO.setRecordList(recordList);
					}
					
					if(new Integer(-1).equals(waimaiVO.getOrderStatus()) || new Integer(0).equals(waimaiVO.getOrderStatus())){
						itemVO.setStatus(-1);
					}
					// status==2已退菜
					if (new Integer(1).equals(itemVO.getIsRefund())) {
						itemVO.setStatus(2);
						continue;
						// status==1待取餐
					} else if (new Integer(1).equals(itemVO.getStatus())) {
						if (!CollectionUtils.isEmpty(orderRecordList)) {
							// 上菜数量大于0 且小于菜品总数量 ，待取餐
							if (itemVO.getServingCount() > 0
									&& Arith.sub(itemVO.getBuyCount(), itemVO.getServingCount()) > 0
									) {
								//上菜的菜品都已经开柜
								if (count == orderRecordList.size()) {
									// 如果kds开启已制作中，则剩下菜品显示已下厨
									if (new Integer(1).equals(itemVO.getMakeStatus())) {
										zeroFlag = true;
										//显示已下厨
										itemVO.setStatus(0);
									} else {
										flag = true;
										// 显示已接单
										itemVO.setStatus(null);
									}
								}
							} else if (itemVO.getServingCount() > 0
									&& Arith.sub(itemVO.getBuyCount(), itemVO.getServingCount()) == 0
									) {
								if(count == orderRecordList.size()){
									// 上菜数量和菜品总数量相同，已取餐
									itemVO.setStatus(3);
								}
							}else if(itemVO.getServingCount()==0 && !new Integer(0).equals(itemVO.getIsPackage())){
								if(count == orderRecordList.size()){
									if(new Integer(1).equals(itemVO.getMakeStatus())){
										zeroFlag = true;
										itemVO.setStatus(0);
									}else{
										itemVO.setStatus(null);
										flag = true;
									}
								}
							}
						}else{
							if(new Integer(1).equals(itemVO.getMakeStatus())){
								zeroFlag = true;
								itemVO.setStatus(0);
							}else{
								itemVO.setStatus(null);
								flag = true;
							}
						}
						//存在普通套餐或组合套餐
					} else{
						if(!CollectionUtils.isEmpty(orderRecordList) && !new Integer(0).equals(itemVO.getIsPackage())){
							//上菜的菜品都已经开柜
							if (count == orderRecordList.size()) {
								// 如果kds开启已制作中，则剩下菜品显示已下厨
								if (new Integer(1).equals(itemVO.getMakeStatus())) {
									zeroFlag = true;
									//显示已下厨
									itemVO.setStatus(0);
								} else {
									flag = true;
									// 显示已接单
									itemVO.setStatus(null);
								}
							}else if(orderRecordList.size()-count>0){
								itemVO.setStatus(1);
							}
						}
					}
				}
				
				if (itemVO.getStatus() == null && !flag) {
					status++;
					// 0 已下厨
				} else if (new Integer(0).equals(itemVO.getStatus()) && !zeroFlag) {
					zeroStatus++;
					// 1待取餐
				} else if (new Integer(1).equals(itemVO.getStatus()) || flag || zeroFlag) {
					oneStatus++;
					// 2拒单
				} else if (new Integer(2).equals(itemVO.getStatus())) {
					twoStatus++;
					// 3已取餐
				} else if (new Integer(3).equals(itemVO.getStatus())) {
					threeStatus++;
				}
			}
			// 待取餐状态
			if (oneStatus > 0 || (threeStatus>0 && (zeroStatus>0 || status>0 || twoStatus>0))) {
				waimaiVO.setPrepMealStatus(1);
			//已取餐状态
			} else if (threeStatus+systemCount == waimaiVO.getWaimaiItems().size()
					|| threeStatus + twoStatus+systemCount == waimaiVO.getWaimaiItems().size()) {
				waimaiVO.setPrepMealStatus(2);
			} else {
				waimaiVO.setPrepMealStatus(0);
			}
		}
		return waimaiVO;
	}
	
	
	/**
	 * 开通kds，获取菜品的取餐柜订单状态、根据菜品状态判断订单状态
	 * @param isOpenKDS
	 * @param waimai
	 * @return
	 */
	public WaimaiExtend waimaiExtendGoodsStatus(Integer isOpenKDS, WaimaiExtend waimai) {
		// 是否开通KDS，开通KDS要判断单个菜品的状态 同时根据菜品状态判断订单状态
		if (new Integer(1).equals(isOpenKDS)
				&& Constants.orderOutSupportId.ONLINE_ORDER.getValue().equals(waimai.getOuterSupportId())
				&& waimai.getItems().size() > 0) {
			int status = 0;
			int zeroStatus = 0;
			int oneStatus = 0;
			int twoStatus = 0;
			int threeStatus = 0;
			int systemCount = 0;
			for (WaimaiItem itemVO : waimai.getItems()) {
				boolean zeroFlag = false;
				boolean flag = false;
				//过滤餐具费、打包费、服务费
				if (CommConstant.SYSTEM_BAG_GOODS.equals(itemVO.getGoodsDesc()) || CommConstant.SYSTEM_BOX_GOODS
						.equals(itemVO.getGoodsDesc()) || CommConstant.SYSTEM_FWF_GOODS.equals(itemVO.getGoodsDesc())) {
					systemCount++;
					continue;
				}else{
					List<CupboardOrderRecord> orderRecordList = null;
					if(itemVO.getItemId()!=null){
						// 获取单个菜品取餐柜柜子状态
						orderRecordList = orderServiceApi.getCupboardGoodsStatus(waimai.getOrderNum(),
								itemVO.getItemId(),	CalendarUtil.formatDateByString(DateUtils.getBeforeDate(24)));
					}else{
						// 获取单个菜品取餐柜柜子状态
						orderRecordList = orderServiceApi.getCupboardGoodsStatus(waimai.getOrderNum(),
								itemVO.getId(),CalendarUtil.formatDateByString(DateUtils.getBeforeDate(24)));
					}
					int count = 0;
					if (!CollectionUtils.isEmpty(orderRecordList)) {
						for (CupboardOrderRecord record : orderRecordList) {
							if (new Integer(2).equals(record.getGoodStatus())) {
								count++;
							}
						}
					}
					if(new Integer(-1).equals(waimai.getOrderStatus()) || new Integer(0).equals(waimai.getOrderStatus())){
						itemVO.setStatus(-1);
					}
					// status==2已退菜
					if (new Integer(1).equals(itemVO.getIsRefund())) {
						itemVO.setStatus(2);
						continue;
						// status==1待取餐
					} else if (new Integer(1).equals(itemVO.getStatus())) {
						if (!CollectionUtils.isEmpty(orderRecordList)) {
							// 上菜数量大于0 且小于菜品总数量 ，待取餐
							if (itemVO.getServingCount() > 0
									&& Arith.sub(itemVO.getBuyCount(), itemVO.getServingCount()) > 0
									) {
								//上菜的菜品都已经开柜
								if (count == orderRecordList.size()) {
									// 如果kds开启已制作中，则剩下菜品显示已下厨
									if (new Integer(1).equals(itemVO.getMakeStatus())) {
										zeroFlag = true;
										//显示已下厨
										itemVO.setStatus(0);
									} else {
										flag = true;
										// 显示已接单
										itemVO.setStatus(null);
									}
								}
							} else if (itemVO.getServingCount() > 0
									&& Arith.sub(itemVO.getBuyCount(), itemVO.getServingCount()) == 0
									) {
								if(count == orderRecordList.size()){
									// 上菜数量和菜品总数量相同，已取餐
									itemVO.setStatus(3);
								}
							}else if(itemVO.getServingCount()==0 && !new Integer(0).equals(itemVO.getIsPackage())){
								if(count == orderRecordList.size()){
									if(new Integer(1).equals(itemVO.getMakeStatus())){
										zeroFlag = true;
										itemVO.setStatus(0);
									}else{
										itemVO.setStatus(null);
										flag = true;
									}
								}
							}
						}else{
							if(new Integer(1).equals(itemVO.getMakeStatus())){
								zeroFlag = true;
								itemVO.setStatus(0);
							}else{
								itemVO.setStatus(null);
								flag = true;
							}
						}
						//存在普通套餐或组合套餐
					} else{
						if(!CollectionUtils.isEmpty(orderRecordList) && !new Integer(0).equals(itemVO.getIsPackage())){
							//上菜的菜品都已经开柜
							if (count == orderRecordList.size()) {
								// 如果kds开启已制作中，则剩下菜品显示已下厨
								if (new Integer(1).equals(itemVO.getMakeStatus())) {
									zeroFlag = true;
									//显示已下厨
									itemVO.setStatus(0);
								} else {
									flag = true;
									// 显示已接单
									itemVO.setStatus(null);
								}
							}else if(orderRecordList.size()-count>0){
								itemVO.setStatus(1);
							}
						}
					}
				}
				if (itemVO.getStatus() == null && !flag) {
					status++;
					// 0 已下厨
				} else if (new Integer(0).equals(itemVO.getStatus()) && !zeroFlag) {
					zeroStatus++;
					// 1待取餐
				} else if (new Integer(1).equals(itemVO.getStatus()) || flag || zeroFlag) {
					oneStatus++;
					// 2拒单
				} else if (new Integer(2).equals(itemVO.getStatus())) {
					twoStatus++;
					// 3已取餐
				} else if (new Integer(3).equals(itemVO.getStatus())) {
					threeStatus++;
				}
			}
			// 待取餐状态
			if (oneStatus > 0 || (threeStatus>0 && (zeroStatus>0 || status>0 || twoStatus>0))) {
				waimai.setPrepMealStatus(1);
			//已取餐状态
			} else if (threeStatus+systemCount == waimai.getItems().size()
					|| threeStatus + twoStatus+systemCount == waimai.getItems().size()) {
				waimai.setPrepMealStatus(2);
			} else {
				waimai.setPrepMealStatus(0);
			}
		}
		return waimai;
	}
	
	
	/**
	 * 根据取餐柜柜子状态判断订单状态
	 * @param waimai
	 * @param orderRecordList
	 * @param orderRecordVOList
	 */
	private void installOrderRecord(WaimaiExtend waimai,List<CupboardOrderRecord> orderRecordList,List<CupboardOrderRecordVO> orderRecordVOList){
		if(!CollectionUtils.isEmpty(orderRecordList)){
			//状态为2
			int statusTwo = 0;
			//状态为0
			int statusZero = 0;
			for(CupboardOrderRecord record:orderRecordList){
				//取餐柜订单中 多个餐柜中只要有一个为1待取餐则这个订单为待取餐 
				if (!new Integer(2).equals(waimai.getPrepMealStatus())
						&& new Integer(1).equals(record.getGoodStatus())) {
					waimai.setPrepMealStatus(1);
				}
				//餐柜的状态为2已取餐
				if(new Integer(2).equals(record.getGoodStatus())){
					statusTwo++;
				}
				//餐柜的状态为0制作中
				if(new Integer(0).equals(record.getGoodStatus())){
					statusZero++;
				}
				CupboardOrderRecordVO orderRecordVO = new CupboardOrderRecordVO();
				BeanUtils.copyProperties(record, orderRecordVO);
				orderRecordVOList.add(orderRecordVO);
			}
			//如果该取餐柜订单已经完成了就不能再跟改状态
			if (!new Integer(2).equals(waimai.getPrepMealStatus())) {
				// 餐柜个数
				int orderSize = orderRecordList.size();
				// 全部都是状态为0的柜台
				if (orderSize == statusZero) {
					waimai.setPrepMealStatus(0);
					// 状态柜台为2的
				} else if (statusTwo == orderSize || ((statusTwo + statusZero) == orderSize)) {
					waimai.setPrepMealStatus(2);
				}
			}
		}
	}
	
	
	@Override
	public CoreResponse<StatusInfo> deleteMyOrderAndRes(String orderNum) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		Waimai waimai = getWaimaiOrderByOrderNum(orderNum);
		if (waimai == null) {
			res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setMsg("取消订单失败,该订单不存在");
			return res;
		}
		if ((new Integer(0).equals(waimai.getOrderStatus()) ||  new Integer(-1).equals(waimai.getOrderStatus())) && new Integer(0).equals(waimai.getPayStatus())) {
			waimai.setOrderStatus(Constants.orderStatus.STATUS_TWELVE.getValue());
			updateWaimaiStauts(waimai);
			res.setMsg("订单取消成功");
		} else {
			res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setMsg("订单取消失败");
		}
		if(!StringUtils.isEmpty(waimai.getKoubeiShopid())){
			waimaiServiceApi.uploadOrder(waimai, waimai.getOrderNum(), koubeiUploadUrl, uploadOrderFlag,waimai.getOuterSupportId());
		}
		//20200610 积分退款
//        payMotionApi.executeRefundPoints(waimai);
		//订单优惠券反核销
//        payMotionApi.cancelVerifyVoucherList(waimai);
		return res;
	}

	@Override
	public CoreResponse<StatusInfo> getGoodsCouponV2(String buyerId, String shopId, Integer storeId, String orderNum,Integer authMode) {

		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		//登录模式判断
		if(!new Integer(2).equals(authMode)){
			authMode = 1;
		}
		ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfo(buyerId, authMode);
		if (null == thirdUserInfo || thirdUserInfo.getSource() != 1) {
			res.setData(null);
			res.setMsg("支付宝顾客信息不存在");
			return res;
		}
		if (shopId == null) {
			// res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setData(null);
			res.setMsg("该店铺暂未绑定口碑shopId");
			return res;
		}

		Shopper shopper = shopperInfoServiceApi.getShopper(storeId);
		storeId = shopper != null ? shopper.getId() : null;
		WaimaiExtend waimai = getWaimaiDeatilsByOrderNum(orderNum);
		if (waimai == null) {
			res.setData(null);
			res.setMsg("订单信息不存在");
			// res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setStatusInfo(StatusInfo.SUCCESS);
			return res;
		}
		List<Integer> goodsIdList = new ArrayList<Integer>();
		if (waimai.getPayStatus() == 0 && (waimai.getOrderStatus() == 0 || waimai.getOrderStatus() == -1
				|| waimai.getOrderStatus() == 1 || waimai.getOrderStatus() == 3)) {
			if (!new Integer(3).equals(waimai.getOrderStatus())) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("shopperId", waimai.getShopId() + "");
				map.put("buyerId", buyerId);
				CommonThread.execute("==========自动领全场券回调结果：", uploadUrl + "/ajax/receiveCoupon.htm", map);
			}
			Set<Integer> goodIds = new HashSet<Integer>();
			if (waimai.getItems() != null && waimai.getItems().size() > 0) {
				for (WaimaiItemExtend item : waimai.getItems()) {
					if (item.getGoodsId() != null && (item.getIsRefund() == null || item.getIsRefund() == 0)) {
						// 只有不是赠菜，并且不是退菜和退菜数量不等于下单数量
						goodIds.add(item.getGoodsId());
					}
				}
				goodsIdList = getGoodsCoupon(thirdUserInfo, storeId, goodIds, shopId.toString());
			}
		}
		if (CollectionUtils.isEmpty(goodsIdList)) {
			res.setMsg("没有优惠商品");
			return res;
		}
		res.setMsg("领取成功");
		return res;
	}

	@Override
	public CoreResponse<GoodsAndOrderStateVO> getGoodsAndOrderState(Integer storeId, String buyerId,
			String tableName,Integer clientOrderMode) {

		CoreResponse<GoodsAndOrderStateVO> res = new CoreResponse<GoodsAndOrderStateVO>();
		GoodsAndOrderStateVO goodsVO = new GoodsAndOrderStateVO();
		
		List<GoodsCartAndDetail> goodsList = null;
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		// 获取店铺配置信息
		Object config = redisServiece.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfig = null;
		if (config != null) {
			shopperConfig = (ShopperConfigExtend) config;
		}else{
			Map<String, Object> configMap = shopperInfoServiceApi.getShopperAllConfig(storeId);
			shopperConfig = SweepOrderUtils.convertToShopperConfigVO(configMap);
		}
		
		// 根据桌台获取订单状态及购物车商品
		if (!StringUtils.isEmpty(tableName)) {
			if (shopperConfig != null && new Integer(1).equals(shopperConfig.getFirstPayMent()) && new Integer(1).equals(shopperConfig.getIsOpenDeskmateSinglePoint())) {
				goodsList = goodsCartServiceApi.getGoodsCartByTableNoAndBuyerId(storeId, tableName, startDate, endDate, buyerId);
			} else {
				goodsList = goodsCartServiceApi.getGoodsCartByTableNo(storeId, tableName, startDate, endDate,clientOrderMode);
			}
		// 根据buyerId 获取订单状态及购物车商品
		} else {
			goodsList = goodsCartServiceApi.getGoodsCartByBuyerId(storeId, buyerId, startDate, endDate,clientOrderMode);
		}
		//购物车所有商品id
		List<Map<String,Object>> sellOutGoodsInfo = null;
		//购物车所有商品数量
		double  goodsCount = 0d;
		// 如果购物车存在商品判断是否存在已售罄商品
		if (!CollectionUtils.isEmpty(goodsList)) {
			List<Integer> idList = new ArrayList<Integer>();
			for (GoodsCartAndDetail goods : goodsList) {
				goodsCount = Arith.add(goods.getBuyCount(), goodsCount);
				idList.add(goods.getGoodsId());
			}
            sellOutGoodsInfo = shopperGoodsServiceApi.isSelloutByGoodsId(storeId, idList, DateUtils.getTodayStartTime(), endDate, DateUtils.getNowTime());
		}
		//查询是否自定义开启自提
		Integer count = shopperInfoServiceApi.getShopperRenovationCustomPage(storeId, "P_Index", "A_Takeout_Show", 1);
		//如果开通在线订单自提且配置了商品限购数量 判断是否大于限购数量
		Map<String,Object> map = new HashMap<String,Object>();
		if (count > 0 && shopperConfig.getPurchaseNum() > 0) {
			if (goodsCount > shopperConfig.getPurchaseNum()) {
				map.put("purchaseNum", shopperConfig.getPurchaseNum());
				map.put("msg", "本店商品限购" + shopperConfig.getPurchaseNum() + "份");
			}
		}
		WaimaiVO waimaiVO = null;
		//获取进行中的订单
		Waimai waimai = getMyOrderStatus(storeId,tableName,buyerId,clientOrderMode);
		if (waimai != null) {
			waimaiVO = new WaimaiVO();
			BeanUtils.copyProperties(waimai, waimaiVO);
			//订单创建时间及支付时间date转换String
			waimaiVO.setCreateTime(DateUtils.getDateChangeString(waimai.getCreateTime()));
			waimaiVO.setPayTime(DateUtils.getDateChangeString(waimai.getPayTime()));
		}
		goodsVO.setWaimai(waimaiVO);
		goodsVO.setSellOutGoodsInfo(sellOutGoodsInfo);
		goodsVO.setPreOrder(map);
		res.setData(goodsVO);
		return res;
	}

	@Override
	public CoreResponse<Map<String,Object>> findOtherPaySucc(String orderNum) {

		logger.info("代付请求成功=======================" + orderNum);
		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		WaimaiExtend waimai = getWaimaiDeatilsByOrderNum(orderNum);
		Map<String,Object> map = new HashMap<String,Object>();
		if (null != waimai && new Integer(0).equals(waimai.getIsOtherPay())) {
			waimai.setIsOtherPay(new Integer(-1));
			updateWaimai(waimai);
			map.put("isOtherPay", new Integer(-1));
			res.setMsg("修改成功");
		} else {
			if(waimai==null){
				map.put("isOtherPay", new Integer(0));
				res.setMsg("修改失败，订单不存在");
			}else {
				map.put("isOtherPay", waimai.getIsOtherPay());
				res.setMsg("修改失败，订单已支付");
			}
		}
		res.setData(map);
		return res;
	}
	
	@Override
	public AlipayApplyAuthToken flushAuthToken(AlipayApplyAuthToken token) {
		try {
			if (token == null) {
				return null;
			}
			// add 2016-09-18 授权刷新 token一定存在
			Map<String, Object> rmap = OpenAuthTokenAppQuery.execute(token.getAppId(), token.getAuthToken());
			if ("true".equals(rmap.get("success").toString())) {
				if (!"valid".equals(rmap.get("status"))) {
					Map<String, Object> rs = RefreshToken.execute(token);
					if ("true".equals(rs.get("success"))) {
						// 更新 AlipayApplyAuthToken returnMap.put("data", app);
						token = (AlipayApplyAuthToken) rs.get("data");
						alipayServiceApi.updateAlipayApplyAuthToken(token);
						token = (AlipayApplyAuthToken) rs.get("data");
						return token;// 成功
					} else {
					}
				} else {
					return token;// 成功
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}



	@Override
	public CoreResponse<SaveWaimaiVO> createWaimaiOrder(CreateWaimaiEntryDto createWaimai) {
		
		CoreResponse<SaveWaimaiVO> res = new CoreResponse<>();
        String memberId = createWaimai.getMemberId();
        // 获取店铺配置
		Object config = redisServiece.getObj(createWaimai.getStoreId()+"_shopperConfig");
		ShopperConfigExtend  shopperConfig = null;
		if(config==null){
			Map<String, Object> configMap = shopperInfoServiceApi.getShopperAllConfig(createWaimai.getStoreId());
			shopperConfig= SweepOrderUtils.convertToShopperConfigVO(configMap);
		}else{
			shopperConfig = (ShopperConfigExtend)config;
		}
		// 预约点餐下单时判断
		Integer reserveTime = shopperConfig.getReserveTime();
		if(new Integer(1).equals(reserveTime)){
			ReserveBasicInfoVO reserveBasicInfoVO = new ReserveBasicInfoVO();
			reserveBasicInfoVO.setShopperId(Integer.valueOf(createWaimai.getShopId()));
			reserveBasicInfoVO.setStoreId(Integer.valueOf(createWaimai.getStoreId()));
			reserveBasicInfoVO.setReserveLatestTime(createWaimai.getReserveLatestTime());
			reserveBasicInfoVO.setReceiveCount(createWaimai.getReceiveCount());
			CoreResponse<String> appointmentVerification = indexService.appointmentVerification(reserveBasicInfoVO,createWaimai.getReserveDate());
			if(StatusInfo.BUSINESS.equals(appointmentVerification.getStatusInfo())){
				res.setStatusInfo(StatusInfo.FORBIDDEN);
				res.setSubMsg("不在预约时间或该时间段已经预约满了");
				return res;
			}
		}

		//登录模式判断
		if(!new Integer(2).equals(createWaimai.getAuthMode())){
			createWaimai.setAuthMode(1);
		}
		// 获取用户信息
		ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfo(createWaimai.getBuyerId(), createWaimai.getAuthMode());
		if(thirdUserInfo==null){
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setSubMsg("获取用户信息失败！请检查参数");
			return  res;
		}
		// 获取桌台信息
		DiningArea tableInfo = null;
		if (createWaimai.getTableInfoId() != null) {
			tableInfo = shopperInfoServiceApi.getDiningAreaById(createWaimai.getTableInfoId());
		}

		// 桌台名称
		String tableName = tableInfo == null ? null : tableInfo.getName();
		SaveWaimaiVO saveWaimai = new SaveWaimaiVO();
		// 获取购物车中商品信息
		List<GoodsCartAndDetail> goodsList = shopCartService.getShopCart(createWaimai.getStoreId(), tableName, createWaimai.getBuyerId(),createWaimai.getClientOrderMode(), shopperConfig.getFirstPayMent(), shopperConfig.getIsOpenDeskmateSinglePoint());
		if (CollectionUtils.isEmpty(goodsList)) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setSubMsg("下单失败,购物车为空");
			res.setData(null);
			return res;
		}
        //解决订单重复问题
        if(tableInfo!=null && tableInfo.getId()!=null){
            Boolean flag = redisServiece.setInxExp(
                    "createWaimai_" + createWaimai.getStoreId() + "_" + tableInfo.getId(), System.currentTimeMillis(),
                    5L, TimeUnit.SECONDS);
            if(!flag ){
                //如果key值存在，则判断是否在3s内，大于3s则继续下单且重新set/key值
                Object time = redisServiece.getObj("createWaimai_"+createWaimai.getStoreId()+"_"+tableInfo.getId());
                if(time!=null){
                    Long currentTime = Long.valueOf(String.valueOf(time));
                    if ((System.currentTimeMillis() - currentTime) < 5000) {
                        res.setSubMsg("订单已被创建");
                        saveWaimai.setFlag(1);
                        res.setData(saveWaimai);
                        return res;
                    }else{
                        redisServiece.remove("createWaimai_" + createWaimai.getStoreId() + "_" + tableInfo.getId());
                        redisServiece.setInxExp(
                                "createWaimai_" + createWaimai.getStoreId() + "_" + tableInfo.getId(), System.currentTimeMillis(),
                                5L, TimeUnit.SECONDS);
                    }
                }
            }
        }
		//获取店铺是否开通口碑正餐后付
		Integer koubeiDinner = shopperConfig.getKoubeiDinner();
		
		// 获取扫码下单（包含无桌台）订单信息
		WaimaiExtend waimai = getCreateWaimai(createWaimai.getStoreId(), tableName,
				createWaimai.getBuyerId(),Constants.clientOrderMode.SCAN_ORDER_MODE.getValue(),koubeiDinner);
		
		// 是否整单打包
		Integer isOut = createWaimai.getIsOut();
		
		// 就餐人数
		Object peopleNumberObj = null;
		if (shopperConfig != null && new Integer(1).equals(shopperConfig.getFirstPayMent()) && new Integer(1).equals(shopperConfig.getIsOpenDeskmateSinglePoint())) {
			peopleNumberObj = redisServiece.getObj(createWaimai.getStoreId()+"_"+tableInfo.getId()+"_"+createWaimai.getBuyerId()+"_peopleNumber");
		} else {
			peopleNumberObj = redisServiece.getObj(createWaimai.getStoreId()+"_"+(tableInfo==null?createWaimai.getBuyerId():tableInfo.getId())+"_peopleNumber");
		}
		Integer peopleNumber = 0;
		
		if(peopleNumberObj==null || Integer.valueOf(String.valueOf(peopleNumberObj))<=0 ){
			peopleNumber = createWaimai.getPeopleNumber() == null ? 0 : createWaimai.getPeopleNumber();
		}else{
			peopleNumber = Integer.valueOf(String.valueOf(peopleNumberObj));
		}
		
		if (waimai != null) {
			isOut = waimai.getIsOut();
		}
		// 获取餐具费
		Double boxGoodsPrice = 0.0;
		Double boxPrice = shopperConfig.getBoxPrice();
		// 获取打包费
		Double bagPrice = shopperConfig.getBagPrice();

		if (!new Integer(1).equals(isOut) && !new Integer(1).equals(koubeiDinner)) {
			if (boxPrice > 0) {
				boxGoodsPrice = Arith.mul(Double.valueOf(peopleNumber), boxPrice);
			}
		}
		String batchNo = "";
		//开通口碑后付功能
		if(new Integer (1).equals(koubeiDinner)){
			// 口碑正餐后付批次号
			batchNo = "sm_"+Utils.createOrderNum(createWaimai.getStoreId());
		}
		WaimaiExtend waimaiExtend = installWaimaiExtend();
		boolean flag = false;
		if (waimai != null) {
			//先吃后付加菜订单
			if (new Integer(1).equals(waimai.getOrderStatus()) && !new Integer(1).equals(waimai.getPayStatus())) {
				waimai.setNote(StringUtils.isEmpty(createWaimai.getNote()) ? "" : createWaimai.getNote());
				waimai.setOrderStatus(Constants.orderStatus.STATUS_THREE.getValue());
				//开通口碑正餐后付set订单版本号每次加菜自增
				if(new Integer(1).equals(koubeiDinner)){
					waimai.setPosVersion(waimai.getPosVersion()==null?2:(waimai.getPosVersion()+1));
					// 口碑正餐后付批次号
					batchNo = "sm_"+Utils.createOrderNum(waimai.getShopId());
				}
				waimaiExtend = saveWaimaiOrderAddFood(waimai, goodsList, createWaimai, thirdUserInfo, bagPrice,
						boxPrice,batchNo,shopperConfig);
			//先付后吃加菜订单
			} else if (new Integer(-1).equals(waimai.getOrderStatus()) && !new Integer(1).equals(waimai.getPayStatus())
					&& new Integer(1).equals(createWaimai.getAddOrder())) {
				waimai.setNote(StringUtils.isEmpty(createWaimai.getNote()) ? "" : createWaimai.getNote());
				waimai.setCreateTime(new Date());
				waimaiExtend = saveWaimaiOrderAddFood(waimai, goodsList, createWaimai, thirdUserInfo, bagPrice,
						boxPrice,batchNo,shopperConfig);
			//先付后吃取消订单
			}else if (new Integer(-1).equals(waimai.getOrderStatus())
					&& !new Integer(1).equals(waimai.getPayStatus())
					&& !new Integer(1).equals(createWaimai.getAddOrder())){
				waimai.setOrderStatus(Constants.orderStatus.STATUS_TWELVE.getValue());
				updateWaimaiStauts(waimai);
				flag = true;
			}else{
				res.setSubMsg("存在进行中订单,创建订单失败");
				return res;
			}
		}
		//订单为空则创建新订单	//或者先付后吃订单重新下单
		if (waimai == null || flag ) {
			//根据storeId查询口碑id
			ThirdPartyAuthorization thirdPartyAuthorization = shopperInfoServiceApi.getThirdPartyAuthorization(createWaimai.getStoreId());
			waimaiExtend.setShopId(createWaimai.getStoreId());
			if(!Utils.isEmpty(thirdPartyAuthorization)){
				waimaiExtend.setKoubeiShopid(thirdPartyAuthorization.getShopId());
			}else{
				waimaiExtend.setKoubeiShopid(null);
			}
			//waimaiExtend.setKoubeiShopid(StringUtils.isEmpty(createWaimai.getShopId()) ? null : createWaimai.getShopId());
			if (tableInfo != null) {
				waimaiExtend.setTableNum(tableInfo.getName());
				waimaiExtend.setTableUid(tableInfo.getUid());
				waimaiExtend.setMachineId(null == shopperConfig.getHostMachineId() ? tableInfo.getMachineId()
						: shopperConfig.getHostMachineId());
				waimaiExtend.setOrderType(0);// 0:正常订单
			} else {
				waimaiExtend.setOrderType(1);// 1:预下单
			}
			Integer orderStatus = new Integer(1).equals(shopperConfig.getFirstPayMent()) ? -1 : 0;
			
			//扫码下单订单来源5
			waimaiExtend.setOuterSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
			//开通口碑正餐后付
			if(new Integer(1).equals(koubeiDinner)){
				//口碑正餐后付订单来源103
				waimaiExtend.setOuterSupportId(Constants.orderOutSupportId.KOUBEI_ORDER.getValue());
				// 是否预约或堂食订单，立即取餐  4个文字不能变动，要根据该字段判断是预约单还是堂食
				waimaiExtend.setReachTime("立即取餐");
				// 0:轻快餐 1:正餐
				waimaiExtend.setSource(1);
				// 口碑正常后付pos订单版本号每次操作需要加1 口碑根据这个标识来确定这笔订单是否修改
				waimaiExtend.setPosVersion(1);
			}
			waimaiExtend.setOrderStatus(orderStatus);
			waimaiExtend.setNote(StringUtils.isEmpty(createWaimai.getNote()) ? "" : createWaimai.getNote());
			waimaiExtend.setPeopleNumber(peopleNumber);
//			waimaiExtend.setOtherPrice(boxGoodsPrice);
			waimaiExtend.setIsOut(isOut);
			waimaiExtend.setIsChainStore(shopperConfig.getIsChainStore());
            waimaiExtend.setUid(createWaimai.getUid());
			waimaiExtend.setOrderSeq(getOrderSeq(createWaimai.getStoreId(), 0));
			waimaiExtend.setOrderNum(Utils.createOrderNum(createWaimai.getStoreId()));
			waimaiExtend.setBuyerId(createWaimai.getBuyerId());
			waimaiExtend.setBuyNick(thirdUserInfo.getNickName() == null ? "吃货" : thirdUserInfo.getNickName());
            // add by ywc 2019年11月4日   增加顾客下单手机号
            if (!Utils.isEmpty(createWaimai.getBuyerPhone())) {
                waimaiExtend.setBuyerMobile(createWaimai.getBuyerPhone());
                waimaiExtend.setBuyerPhone(createWaimai.getBuyerPhone());
            }
            //获取扫码预约配送redis人数
    		if(new Integer(1).equals(reserveTime)){
    			String reserveDate = createWaimai.getReserveDate();
    			String appointmentTime = createWaimai.getAppointmentTime();
    			waimaiExtend.setReachTime(reserveDate+" "+appointmentTime);
    			waimaiExtend.setOrderType(4);
    			waimaiExtend.setDeliveryStatus(0);
    			//预约配送模式，如果预约了明天的订单，取餐号需要修改
    			waimaiExtend.setOrderSeq(Utils.getReserveOrderSeq(waimaiExtend.getOrderSeq(), reserveDate));
    		}
    		//创建订单
			waimaiExtend = saveWaimaiOrder(waimaiExtend, goodsList, createWaimai, thirdUserInfo, bagPrice, boxPrice,batchNo);
		}

		Integer renovationPage = 0;
		if (new Integer(0).equals(shopperConfig.getFirstPayMent())) {
			// 是否支持柜台收银、根据装修平台配置
			int decorationType = 0;
			if((Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue()).equals(createWaimai.getClientOrderMode())){
				decorationType=1;
			}
			renovationPage = shopperInfoServiceApi.getShopperRenovationCustomPage(createWaimai.getStoreId(),"P_Order_Confirm","A_Prompt_Counter_Pay",decorationType);
		}

		// add by ywc 2019年11月27日 	增加下单消息保存
		if (waimaiExtend != null) {
			Long hostMachineId = null == shopperConfig.getHostMachineId() ? tableInfo.getMachineId()
					: shopperConfig.getHostMachineId();
			// add by ywc 2019年12月11日 	后付订单下单或加菜改为后端推送消息
			String msgCode = Utils.createOrderNum(waimaiExtend.getShopId());
			if (waimaiExtend.getOrderStatus() == 0 || waimaiExtend.getOrderStatus() == 3) {
				// add by ywc 2019年11月27日 	增加下单消息保存
				if (shopperConfig.getSweepPayPrint() == 1) {
					Waimai order = new Waimai();
					BeanUtils.copyProperties(waimaiExtend, order);
					webMsgService.sendWebMsg(order, tableInfo.getMachineId(), 1, shopperConfig.getAliyunMqtt(), hostMachineId, msgCode);
					webMsgService.saveAddWaimaiMsgRecord(shopperConfig.getSweepPayPrint(), waimaiExtend, tableInfo, hostMachineId, msgCode);
				}
			}
		}

	   //获取扫码预约配送redis单量 add hyc 2019年11月29日11:23:36
       Integer reserveStatus = createWaimai.getReserveStatus();
       if (new Integer(1).equals(reserveTime) && !new Integer(-1).equals(reserveStatus)) {
           String key = KeyGenerateRulesUtils.getAppointmentTimeKey(createWaimai.getShopId(), String.valueOf(createWaimai.getStoreId()),
           		createWaimai.getReserveDate(),createWaimai.getAppointmentTime());
           Integer num = redisServiece.getObj(key) == null ? 0 : Integer.valueOf(redisServiece.getObj(key).toString());
           redisServiece.setObj(key, num + 1, 48 * 60 * 60 * 1000L,TimeUnit.SECONDS);
       }

		//如果先吃后付模式且 开启柜台收银则不上传订单
		if (StringUtils.isNotEmpty(createWaimai.getShopId()) && (!new Integer(0).equals(shopperConfig.getFirstPayMent())) || (!new Integer(1).equals(renovationPage))){ 
			Waimai order = new Waimai();
			BeanUtils.copyProperties(waimaiExtend, order);
			// 调用支付宝上传接口上传订单 
			waimaiServiceApi.uploadOrder(order, waimaiExtend.getOrderNum(), koubeiUploadUrl, uploadOrderFlag,waimaiExtend.getOuterSupportId());
		}
		if(tableInfo!=null && tableInfo.getId()!=null){
			//删除redis存储的key
			redisServiece.remove("createWaimai_" + createWaimai.getStoreId() + "_" + tableInfo.getId());
		}
		
		if (null != thirdUserInfo) {
			// add by yxy 2019年3月19日 15:00:39 创建订单时保存订单操作关联表 
			WaimaiOperateRelated operateRelated = new WaimaiOperateRelated();
			// 商家Id
			operateRelated.setShopId(waimaiExtend.getShopperId());
			// 店铺Id
			operateRelated.setStoreId(waimaiExtend.getShopId());
			// 订单号
			operateRelated.setOrderNum(waimaiExtend.getOrderNum());
			// 订单来源
			operateRelated.setOuterSupportId(waimaiExtend.getOuterSupportId());
			// 订单下单时间
			operateRelated.setOrderDate(waimaiExtend.getCreateTime());
			// 操作时间类型
			if (new Integer(3).equals(waimaiExtend.getOrderStatus())) {
				// 先吃后付加菜订单
				operateRelated.setTimeType(CommonConstants.WaimaiOperateTimeType.ADD_ORDER.getValue());
			} else if (null != waimai && new Integer(-1).equals(waimaiExtend.getOrderStatus()) && !new Integer(1).equals(waimai.getPayStatus())
					&& new Integer(1).equals(createWaimai.getAddOrder())) {
				// 先付后吃加菜订单
				operateRelated.setTimeType(CommonConstants.WaimaiOperateTimeType.ADD_ORDER.getValue());
			} else {
				operateRelated.setTimeType(CommonConstants.WaimaiOperateTimeType.ORDER.getValue());
			}
			// 操作时间
			operateRelated.setOperateTime(new Date());
			// 操作人员类型
			operateRelated.setOperatorType(CommonConstants.WaimaiOperatorType.CUSTOMER.getValue());
			// 操作人员Id
			operateRelated.setOperatorId(thirdUserInfo.getId());
			// 操作人员员工号 扫码点餐不存
			operateRelated.setOperatorNum(null);
			// 操作人员的昵称或者名称
			operateRelated.setOperatorNick(thirdUserInfo.getNickName() == null ? "吃货" : thirdUserInfo.getNickName());
			// 订单创建时间
			operateRelated.setCreateTime(new Date());
			waimaiServiceApi.saveWaimaiOperateRelated(operateRelated);
		}
		saveWaimai.setOrderNum(waimaiExtend.getOrderNum());
		saveWaimai.setOrderStatus(waimaiExtend.getOrderStatus());
		saveWaimai.setHexiaoType(waimaiExtend.getHexiaoType());
		saveWaimai.setIsOut(waimaiExtend.getIsOut());
		saveWaimai.setOriginalPrice(waimaiExtend.getOriginalPrice());
		saveWaimai.setPayStatus(waimaiExtend.getPayStatus());
		saveWaimai.setReachTime(waimaiExtend.getReachTime());
		saveWaimai.setSource(waimaiExtend.getSource());
		saveWaimai.setBatchNo(batchNo);
		res.setSubMsg("订单创建成功");
		res.setData(saveWaimai);
		return res;
	}
	
	private WaimaiExtend installWaimaiExtend() {
		WaimaiExtend waimaiExtend = new WaimaiExtend();
		waimaiExtend.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
		waimaiExtend.setIsPrint(0);
		waimaiExtend.setIsHexiao(0);
		waimaiExtend.setThirdPromotionFee(0.0d);
		waimaiExtend.setPayplatformPromotionFee(0.0d);
		waimaiExtend.setHexiaoType(0);
		waimaiExtend.setIsCheckout(0);
		waimaiExtend.setSource(0);
		waimaiExtend.setIsOtherPay(0);
		waimaiExtend.setPromotionPrice(0.0d);
		waimaiExtend.setIsAlipayOrder(0);
		waimaiExtend.setIsPromotion(0);
		waimaiExtend.setIsDelete(0);
		waimaiExtend.setPayModel(10);
		waimaiExtend.setIsOpenInvoice(0);
		waimaiExtend.setIsRid(0);
		waimaiExtend.setRidPrice(0.0d);
		waimaiExtend.setPrepMealStatus(0);
		waimaiExtend.setOrderType(0);
		return waimaiExtend;
	}

	@Override
	public List<WaimaiExtend> getOnlineOrderHexiao(Integer storeId, String buyerId,Integer clientOrderMode) {
		WaimaiParam param = new WaimaiParam();
		param.setBuyerId(buyerId);
		param.setStoreId(storeId);
		param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
		param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
		param.setIsHexiao(0);
		param.setStatus(Constants.orderStatus.STATUS_ONE.getValue());
		param.setHexiaoType(0);
		List<WaimaiExtend> waimai = waimaiServiceApi.getOnlineOrderHexiao(param);
		return waimai;
	}

	@Override
	public CoreResponse<SaveWaimaiVO> createOnlineOrder(CreateWaimaiEntryDto createWaimai) {
		CoreResponse<SaveWaimaiVO> res = new CoreResponse<SaveWaimaiVO>();
        String memberId = createWaimai.getMemberId();
        // 获取店铺配置
		Object config = redisServiece.getObj(createWaimai.getStoreId()+"_shopperConfig");
		ShopperConfigExtend  shopperConfig = null;
		if(config==null){
			Map<String, Object> configMap = shopperInfoServiceApi.getShopperAllConfig(createWaimai.getStoreId());
			shopperConfig= SweepOrderUtils.convertToShopperConfigVO(configMap);
		}else{
			shopperConfig = (ShopperConfigExtend)config;
		}
		// 预约点餐下单时判断
		Integer reserveTime = shopperConfig.getReserveTime();
		if(new Integer(1).equals(reserveTime)){
			ReserveBasicInfoVO reserveBasicInfoVO = new ReserveBasicInfoVO();
			reserveBasicInfoVO.setShopperId(Integer.valueOf(createWaimai.getShopId()));
			reserveBasicInfoVO.setStoreId(Integer.valueOf(createWaimai.getStoreId()));
			reserveBasicInfoVO.setReserveLatestTime(createWaimai.getReserveLatestTime());
			reserveBasicInfoVO.setReceiveCount(createWaimai.getReceiveCount());
			CoreResponse<String> appointmentVerification = indexService.appointmentVerification(reserveBasicInfoVO,createWaimai.getReserveDate());
			if(StatusInfo.BUSINESS.equals(appointmentVerification.getStatusInfo())){
				res.setStatusInfo(StatusInfo.FORBIDDEN);
				res.setSubMsg(appointmentVerification.getMsg());
				return res;
			}
		}
		//登录模式判断
		if(!new Integer(2).equals(createWaimai.getAuthMode())){
			createWaimai.setAuthMode(1);
		}
		// 获取用户信息
		ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfo(createWaimai.getBuyerId(), createWaimai.getAuthMode());
		if(thirdUserInfo==null){
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setSubMsg("获取用户信息失败！请检查参数");
			return  res;
		}

		SaveWaimaiVO saveWaimai = new SaveWaimaiVO();

		// 获取购物车中商品信息
		List<GoodsCartAndDetail> goodsList = shopCartService.getShopCart(createWaimai.getStoreId(), null,
				createWaimai.getBuyerId(),createWaimai.getClientOrderMode(), null, null);
		if (CollectionUtils.isEmpty(goodsList)) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setSubMsg("下单失败,购物车为空");
			res.setData(null);
			return res;
		}

        //解决订单重复问题
        Boolean flag = redisServiece.setInxExp(
                "createWaimai_" + createWaimai.getStoreId() + "_" + createWaimai.getBuyerId(), System.currentTimeMillis(),
                5L, TimeUnit.SECONDS);
        if(!flag ){
            //如果key值存在，则判断是否在3s内，大于3s则继续下单且重新set/key值
            Object time = redisServiece.getObj("createWaimai_"+createWaimai.getStoreId()+"_"+createWaimai.getBuyerId());
            if(time!=null){
                Long currentTime = Long.valueOf(String.valueOf(time));
                if ((System.currentTimeMillis() - currentTime) < 5000) {
                    res.setSubMsg("订单已被创建");
                    saveWaimai.setFlag(1);
                    res.setData(saveWaimai);
                    return res;
                }else{
                    redisServiece.remove("createWaimai_" + createWaimai.getStoreId() + "_" + createWaimai.getBuyerId());
                    redisServiece.setInxExp(
                            "createWaimai_" + createWaimai.getStoreId() + "_" + createWaimai.getBuyerId(), System.currentTimeMillis(),
                            5L, TimeUnit.SECONDS);
                }
            }
        }

//		WaimaiExtend waimai = getCreateWaimai(createWaimai.getStoreId(), null,
//				createWaimai.getBuyerId(),4);
//		if(waimai!=null){
//			res.setSubMsg("存在订单");
//			return res;
//		}
		// 是否整单打包
		Integer isOut = createWaimai.getIsOut();

		// 就餐人数
		Object peopleNumberObj = redisServiece.getObj(createWaimai.getStoreId()+"_"+createWaimai.getBuyerId()+"_peopleNumber");
		Integer peopleNumber = 0;
		
		if(peopleNumberObj==null || Integer.valueOf(String.valueOf(peopleNumberObj))<=0 ){
			peopleNumber = createWaimai.getPeopleNumber() == null ? 0 : createWaimai.getPeopleNumber();
		}else{
			peopleNumber = Integer.valueOf(String.valueOf(peopleNumberObj));
		}
		
		// 获取餐具费
		Double boxGoodsPrice = 0.0;
		Double boxPrice = shopperConfig.getBoxPrice();
		// 获取打包费
		Double bagPrice = shopperConfig.getBagPrice();

		if (!new Integer(1).equals(isOut)) {
			if (boxPrice > 0) {
				boxGoodsPrice = Arith.mul(Double.valueOf(peopleNumber), boxPrice);
			}
		}
		//根據storeId查詢口碑id
		ThirdPartyAuthorization thirdPartyAuthorization = shopperInfoServiceApi.getThirdPartyAuthorization(createWaimai.getStoreId());
		WaimaiExtend waimaiExtend = installWaimaiExtend();
		if(!Utils.isEmpty(thirdPartyAuthorization)){
			waimaiExtend.setKoubeiShopid(thirdPartyAuthorization.getShopId());
		}else{
			waimaiExtend.setKoubeiShopid(null);
		}

		//waimaiExtend.setKoubeiShopid(StringUtils.isEmpty(createWaimai.getShopId()) ? null : createWaimai.getShopId());
		waimaiExtend.setShopId(createWaimai.getStoreId());
		waimaiExtend.setOrderStatus(-1);
		waimaiExtend.setOuterSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
		waimaiExtend.setNote(StringUtils.isEmpty(createWaimai.getNote()) ? "" : createWaimai.getNote());
		waimaiExtend.setPeopleNumber(peopleNumber);
		waimaiExtend.setOtherPrice(boxGoodsPrice);
		waimaiExtend.setIsOut(isOut);
		waimaiExtend.setIsChainStore(shopperConfig.getIsChainStore());
		waimaiExtend.setUid(createWaimai.getUid());
		//在线订单新增订单序号初始值
		if(shopperConfig.getInitOrderSeq()!=null){
			waimaiExtend.setOrderSeq(shopperConfig.getInitOrderSeq()+getOrderSeq(createWaimai.getStoreId(), 0));
		}else{
			waimaiExtend.setOrderSeq(getOrderSeq(createWaimai.getStoreId(), 0));
		}
		//取餐号
		String takeMealNum = Utils.getOrderSeq(waimaiExtend.getOrderSeq());
		waimaiExtend.setOrderNum(Utils.createOrderNum(createWaimai.getStoreId()));
		waimaiExtend.setBuyerId(createWaimai.getBuyerId());
		waimaiExtend.setBuyNick(thirdUserInfo.getNickName() == null ? "吃货" : thirdUserInfo.getNickName());
		if(!StringUtils.isEmpty(createWaimai.getBuyerPhone()) && !("8006663907").equals(createWaimai.getBuyerPhone())){
			waimaiExtend.setBuyerPhone(createWaimai.getBuyerPhone());
		}
		//在线订单自提顾客就餐时间
		if(createWaimai.getReachTime()!=null && !StringUtils.isEmpty(createWaimai.getReachTime())){
			waimaiExtend.setReachTime(createWaimai.getReachTime());
		}
		 //获取扫码预约配送redis人数
		if(new Integer(1).equals(reserveTime)){
			String reserveDate = createWaimai.getReserveDate();
			String appointmentTime = createWaimai.getAppointmentTime();
			waimaiExtend.setReachTime(reserveDate+" "+appointmentTime);
			waimaiExtend.setOrderType(4);
			//预约配送模式，如果预约了明天的订单，取餐号需要修改
			waimaiExtend.setOrderSeq(Utils.getReserveOrderSeq(waimaiExtend.getOrderSeq(), reserveDate));
		}
		//在线订单未开启核销则不需要核销
		if(!new Integer(1).equals(shopperConfig.getOpenHexiao())){
			waimaiExtend.setHexiaoType(1);
			waimaiExtend.setOrderType(1);
		}
		//在线订单开启智能取餐柜
		RelMachineHardWare hardWare = null;
		String takeMealCode = "";
		if(new Integer(1).equals(shopperConfig.getIntelligenceCabinet())){
			waimaiExtend.setOrderType(2);
			RelMachineHardWare machineHard = new RelMachineHardWare();
			machineHard.setStoreId(createWaimai.getStoreId());
			machineHard.setType(2);
			machineHard.setThirdMachineBrand("pinyuan");
			//查询如果有品元的机器，则要判断取餐码唯一性
			hardWare = orderServiceApi.getMachineHardWareInfo(machineHard);
			if(hardWare!=null){
				//如果开启取餐柜要检查验证码是否唯一
				String identifyingCode = checkIdentifyingCode(createWaimai.getStoreId());
				if(!StringUtils.isEmpty(identifyingCode)){
					waimaiExtend.setIdentifyingCode(identifyingCode);
				}
				
				if(new Integer(2).equals(hardWare.getVersion())){
					// 根据订单来源查询订单来源类型
					 OuterSupport outerSupport= shopperInfoServiceApi.getOuterSupportById(4L);
					// 智慧餐厅新生成17位取餐码规则
					takeMealCode = Utils.createTakeMealCode(String.valueOf(hardWare.getMachineId()), Utils.getOrderSeq(waimaiExtend.getOrderSeq()),outerSupport.getOrderCode());
					waimaiExtend.setTakeMealCode(takeMealCode);
				}
			}
		}
		//直接set验证码
		if(StringUtils.isEmpty(waimaiExtend.getIdentifyingCode())){
			String random = createWaimai.getStoreId()+RandomUtil.getRandomNum(10);
			String identifyingCode = RandomUtil.getRandomString(random, 6);
			waimaiExtend.setIdentifyingCode(identifyingCode);
		}
		//保存订单信息
		waimaiExtend = saveOnlineOrder(waimaiExtend, goodsList, createWaimai, thirdUserInfo, bagPrice, boxPrice,shopperConfig);
		//判断如果是用的是品元智能取餐柜，则要保存取餐码、订单号
		if(new Integer(1).equals(shopperConfig.getIntelligenceCabinet()) && hardWare!=null && new Integer(0).equals(shopperConfig.getIsOpenKDS())){
			CupboardOrderRecord orderRecord = new CupboardOrderRecord();
			orderRecord.setOrderNum(waimaiExtend.getOrderNum());
			orderRecord.setCupboardId(String.valueOf(hardWare.getId()));
			orderRecord.setGoodStatus(0);
			orderRecord.setOperateTime(DateUtils.currentTime());
			orderRecord.setState(0);
			orderRecord.setStoreId(waimaiExtend.getShopId());
			orderRecord.setShopId(waimaiExtend.getShopperId());
			orderRecord.setTakeMealNum(takeMealNum);
			if(new Integer(2).equals(hardWare.getVersion())){
				orderRecord.setTakeCode(waimaiExtend.getTakeMealCode());
			}else{
				orderRecord.setTakeCode(waimaiExtend.getIdentifyingCode());
				orderServiceApi.saveCupboardOrderRecord(orderRecord);
			}
		}

		 //获取扫码预约配送redis单量 add hyc 2019年11月29日11:23:36
        Integer reserveStatus = createWaimai.getReserveStatus();
        if (new Integer(1).equals(reserveTime) && !new Integer(-1).equals(reserveStatus)) {
            String key = KeyGenerateRulesUtils.getAppointmentTimeKey(createWaimai.getShopId(), String.valueOf(createWaimai.getStoreId()),
            		createWaimai.getReserveDate(),createWaimai.getAppointmentTime());
            Integer num = redisServiece.getObj(key) == null ? 0 : Integer.valueOf(redisServiece.getObj(key).toString());
            redisServiece.setObj(key, num + 1, 48 * 60 * 60 * 1000L,TimeUnit.SECONDS);
        }

		// 调用支付宝上传接口上传订单
		Waimai waimai = new Waimai();
		BeanUtils.copyProperties(waimaiExtend, waimai);
		waimaiServiceApi.uploadOrder(waimai, waimaiExtend.getOrderNum(), koubeiUploadUrl, uploadOrderFlag,waimaiExtend.getOuterSupportId());
		//box_waimai_time_related创建修改订单操作相关时间  
//		Object dateObj = redisServiece.getObj(createWaimai.getStoreId() + "_" + createWaimai.getBuyerId()+"_scanTime");
//		WaimaiTimeRelated timeRelated = new WaimaiTimeRelated();
//		timeRelated.setShopId(waimaiExtend.getShopperId());
//		timeRelated.setStoreId(waimaiExtend.getShopId());
//		timeRelated.setOrderNum(waimaiExtend.getOrderNum());
//		timeRelated.setOuterSupportId(waimaiExtend.getOuterSupportId());
//		timeRelated.setStartOrderTime(dateObj==null?new Date():(Date)dateObj);
//		timeRelated.setCreateTime(waimaiExtend.getCreateTime());
//		waimaiServiceApi.saveAndUpdateWaimaiTimeRelated(timeRelated);
		if (null != thirdUserInfo) {
			// add by yxy 2019年3月19日 15:00:39 创建订单时保存订单操作关联表 
			WaimaiOperateRelated operateRelated = new WaimaiOperateRelated();
			// 商家Id
			operateRelated.setShopId(waimaiExtend.getShopperId());
			// 店铺Id
			operateRelated.setStoreId(waimaiExtend.getShopId());
			// 订单号
			operateRelated.setOrderNum(waimaiExtend.getOrderNum());
			// 订单来源
			operateRelated.setOuterSupportId(waimaiExtend.getOuterSupportId());
			// 订单下单时间
			operateRelated.setOrderDate(waimaiExtend.getCreateTime());
			// 操作时间类型
			operateRelated.setTimeType(CommonConstants.WaimaiOperateTimeType.ORDER.getValue());
			// 操作时间
			operateRelated.setOperateTime(new Date());
			// 操作人员类型
			operateRelated.setOperatorType(CommonConstants.WaimaiOperatorType.CUSTOMER.getValue());
			// 操作人员Id
			operateRelated.setOperatorId(thirdUserInfo.getId());
			// 操作人员员工号 扫码点餐不存
			operateRelated.setOperatorNum(null);
			// 操作人员的昵称或者名称
			operateRelated.setOperatorNick(thirdUserInfo.getNickName() == null ? "吃货" : thirdUserInfo.getNickName());
			// 订单创建时间
			operateRelated.setCreateTime(new Date());
			waimaiServiceApi.saveWaimaiOperateRelated(operateRelated);
		}
		//删除redis存储的创建订单时重复下单的key
		redisServiece.remove("createWaimai_" + createWaimai.getStoreId() + "_" + createWaimai.getBuyerId());
		redisServiece.remove(createWaimai.getStoreId() + "_" + createWaimai.getBuyerId()+"_scanTime");
		saveWaimai.setOrderNum(waimaiExtend.getOrderNum());
		saveWaimai.setOrderStatus(waimaiExtend.getOrderStatus());
		res.setSubMsg("订单创建成功");
		res.setData(saveWaimai);
		return res;
	}
	
	/**
	 * 
	 * @param storeId
	 * @return
	 */
	private String checkIdentifyingCode(Integer storeId){
		String identifyingCode = "";
		int count = 0; 
		while (count < 3) {
			String code = storeId + RandomUtil.getRandomNum(10);
			identifyingCode = RandomUtil.getRandomString(code, 6);
			CupboardOrderRecord orderRecord = new CupboardOrderRecord();
			orderRecord.setTakeCode(identifyingCode);
			List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
			if (CollectionUtils.isEmpty(orderRecordList)) {
				break;
			}
			count++;
		}
		return identifyingCode;
	}
	
	/**
	 * 保存在线订单信息
	 * @param waimaiExtend
	 * @param goodsList
	 * @param createWaimai
	 * @param thirdUserInfo
	 * @param bagPrice
	 * @param boxPrice
	 */
	@SuppressWarnings("unchecked")
	private WaimaiExtend saveOnlineOrder(WaimaiExtend waimaiExtend, List<GoodsCartAndDetail> goodsList,
                                         CreateWaimaiEntryDto createWaimai, ThirdUserInfo thirdUserInfo, Double bagPrice, Double boxPrice,ShopperConfigExtend shopperConfigExtend) {
		List<WaimaiItemExtend> waimaiItem = new ArrayList<WaimaiItemExtend>();
		Map<String, Object> itemMap = new HashMap<String, Object>();
		//保存订单项信息
		itemMap = saveItem(waimaiExtend, goodsList, bagPrice, createWaimai, thirdUserInfo, new Integer(0), boxPrice,null);
		Double totalPrices = itemMap.get("totalPrices") == null ? 0.0 : (double) itemMap.get("totalPrices");
        double totalOriginalPrice = itemMap.get("totalOriginalPrice") == null ? 0.0d : (double) itemMap.get("totalOriginalPrice");
        double bagTotalPrice = itemMap.get("bagTotalPrice") == null ? 0.0d : (double) itemMap.get("bagTotalPrice");

        waimaiItem = (List<WaimaiItemExtend>) itemMap.get("waimaiItem");

        double otherPrice = Utils.isEmpty(waimaiExtend.getOtherPrice()) ? 0D : waimaiExtend.getOtherPrice();
		waimaiExtend.setTotalPrice(Arith.add(totalPrices, otherPrice));
		waimaiExtend.setOriginalPrice(Arith.add(totalOriginalPrice, otherPrice));
		waimaiExtend.setItems(waimaiItem);

        //在线订单 店内吃算餐盒费、带走算打包费
        if(Utils.isEmpty(waimaiExtend.getOtherPrice()) || waimaiExtend.getOtherPrice() == 0){
            waimaiExtend.setOtherPrice(bagTotalPrice);
        }

		ShopperAndParent shopper = shopperInfoServiceApi.getShopperAndParent(createWaimai.getStoreId());
        if (Utils.isEmpty(shopper.getMinLogo())) {
            shopper.setMinLogo(shopper.getParentInfo().getMinLogo());
        }
			waimaiExtend.setShopperId(shopper.getParentId());
			waimaiExtend.setShopperName(shopper.getParentInfo().getNick());
			waimaiExtend.setShopName(shopper.getNick());
			waimaiExtend.setShopAddress(shopper.getAddress());
			waimaiExtend.setShopContactPhone(shopper.getContactPhone());
			if (shopper.getMinLogo() != null) {
				waimaiExtend.setShopLogo(shopper.getMinLogo());
			} else {
				waimaiExtend.setShopLogo("/res/css/custom/shop_min.png");
			}
		waimaiExtend.setCreateTime(new Date());
		waimaiExtend.setPayStatus(Constants.payStatus.PAYSTATUS_ZERO.getValue());
		waimaiExtend.setTotalPay(0.0);
		logger.info("创建新订单时生成的订单号++++++++++++++orderNum="+waimaiExtend.getOrderNum()+"++++buyerId="+thirdUserInfo.getThirdUserId()+"++tableInfo="+waimaiExtend.getTableNum()+"++goodsCart="+(goodsList==null?null:goodsList.size()));
		//创建订单同时，删除购物车放到同一个事物中
		waimaiServiceApi.saveWaimai(waimaiExtend,shopperConfigExtend ,createWaimai);

		return waimaiExtend;
	}

	@Override
	public CoreResponse<List<WaimaiVO>> orderHexiao(Integer storeId,String buyerId,Integer clientOrderMode) {
		 CoreResponse<List<WaimaiVO>> res = new  CoreResponse<List<WaimaiVO>>();
		//查询未核销订单
		List<WaimaiExtend> waimaiList = getOnlineOrderHexiao(storeId,buyerId,clientOrderMode);
		if(waimaiList==null){
			res.setMsg("暂无未核销订单");
			return res;
		}
		List<WaimaiVO> waimaiVOList= new ArrayList<WaimaiVO>();
		for (WaimaiExtend waimai : waimaiList) {
			WaimaiVO waimaiVO = new WaimaiVO();
			BeanUtils.copyProperties(waimai, waimaiVO);
			//不足四位补零
			if(waimai.getOrderSeq()!=null){
				waimaiVO.setOrderSeq(Utils.getOrderSeq(waimai.getOrderSeq()));
			}
			//订单创建时间及支付时间date转换String
			waimaiVO.setCreateTime(DateUtils.getDateChangeString(waimai.getCreateTime()));
			waimaiVO.setPayTime(DateUtils.getDateChangeString(waimai.getPayTime()));
			
			if(!CollectionUtils.isEmpty(waimai.getItems())){
				for(WaimaiItemExtend item:waimai.getItems()){
					if(item!=null){
						WaimaiItemVO itemVO = new WaimaiItemVO();
						BeanUtils.copyProperties(item, itemVO);
						itemVO.setPropName(item.getPropDesc());
						waimaiVO.getWaimaiItems().add(itemVO);
					}
				}
			}
			waimaiVOList.add(waimaiVO);
		}
		res.setData(waimaiVOList);
		res.setMsg("查询成功");
		return res;
	}

	@Override
	public CoreResponse<UpdateOrderHexiaoVO> updateOrderHexiao(OrderHexiaoEntryVO orderHexiaoEntry) {
		CoreResponse<UpdateOrderHexiaoVO> res = new CoreResponse<UpdateOrderHexiaoVO>();
		UpdateOrderHexiaoVO orderHexiao = new UpdateOrderHexiaoVO();
		List<String> orderNums = new ArrayList<String>();
		List<String> takeCodes = new ArrayList<String>();
		//获取店铺配置
		Object config=redisServiece.getObj(orderHexiaoEntry.getStoreId()+"_shopperConfig");
        ShopperConfigExtend shopperConfig;
        if(config==null){
            // 查询店铺所有配置
            Map<String, Object> configMap = shopperInfoServiceApi.getShopperAllConfig(orderHexiaoEntry.getStoreId());
            // map转成对象
            shopperConfig = SweepOrderUtils.convertToShopperConfigVO(configMap);
		}else{
            shopperConfig = (ShopperConfigExtend)config;
        }
		String orderSeq = "";
		if(new Integer(1).equals(shopperConfig.getOpenHexiao())){
			//查询该店铺下是否存在顾客的核销订单
			List<WaimaiExtend> waimaiList = getOnlineOrderHexiao(orderHexiaoEntry.getStoreId(),orderHexiaoEntry.getBuyerId(),null);
			if(CollectionUtils.isEmpty(waimaiList)){
				res.setSubMsg("暂无未核销订单");
				return res;
			}
			int count = 0;
			for(WaimaiExtend waimaiExtend:waimaiList){
				Waimai waimai = new Waimai();
				waimai.setId(waimaiExtend.getId());
				waimai.setHexiaoType(1);
				if(!StringUtils.isEmpty(orderHexiaoEntry.getTableNum())){
					waimai.setTableNum(orderHexiaoEntry.getTableNum());
				}
				if(!StringUtils.isEmpty(orderHexiaoEntry.getTableUid())){
					waimai.setTableUid(orderHexiaoEntry.getTableUid());
				}
				waimai.setOrderStatus(11);
				waimai.setIsHexiao(1);
				//修改订单核销状态
				count = waimaiServiceApi.updateWaimai(waimai)+count;
				if(count>0){
					orderNums.add(waimaiExtend.getOrderNum());
					takeCodes.add(waimaiExtend.getIdentifyingCode());
					orderSeq = Utils.getOrderSeq(waimaiExtend.getOrderSeq())+","+orderSeq;
					BeanUtils.copyProperties(waimaiExtend, waimai);
					//上传口碑订单
					waimaiServiceApi.uploadOrder(waimai, waimaiExtend.getOrderNum(), koubeiUploadUrl, uploadOrderFlag,waimaiExtend.getOuterSupportId());
				}
			}
			if(count>0){
				res.setSubMsg("核销成功");
			}else{
				res.setSubMsg("核销失败");
			}
		}else{
			res.setSubMsg("该店铺暂未开通核销配置功能");
		}
		orderHexiao.setOrderNum(orderNums);
		orderHexiao.setTakeCode(takeCodes);
		if(!StringUtils.isEmpty(orderSeq)){
			orderSeq = orderSeq.substring(0,orderSeq.length()-1);
			orderHexiao.setOrderSeq(orderSeq);
		}
		res.setData(orderHexiao);
		return res;
	}

	@Override
	public CoreResponse<SweepCloseVO> getSweepClose(Integer storeId,Integer clientOrderMode) {
		CoreResponse<SweepCloseVO> res = new CoreResponse<SweepCloseVO>();
		SweepCloseVO sweepCloseVO = new SweepCloseVO();;
		//获取店铺配置信息
		Object config = redisServiece.getObj(storeId+"_shopperConfig");
		ShopperConfigExtend shopperConfig=null;
		if(config==null){
			// 查询店铺所有配置
			Map<String, Object> configMap = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfig = SweepOrderUtils.convertToShopperConfigVO(configMap);
		}else{
			shopperConfig = (ShopperConfigExtend)config;
		}
		//在线订单判断是否开启营业时间在支付的时候再判断（因为在线订单下单后未支付顾客可以自己删除）
		Integer buttom = 0;
		if(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)){
			buttom = shopperConfig.getOnlineOrder();
		}else{
			buttom = shopperConfig.getIsOpenSweepOrder();
		}
		if(new Integer(1).equals(buttom)){
			//查询承接端是否开启接单按钮
			SweepClose sweepClose = businessInfoApi.getSweepCloseByStoreId(storeId);
			if (sweepClose != null) {
				sweepClose.setTime(sweepClose.getTime() + 1);
				long between= 0l;
				long hour = 0l;
				long min = 0l;
				long s = 0l;
				long warnTime = 0l;
				if(sweepClose.getCloseTime()!=null){
					between = (new Date().getTime() - sweepClose.getCloseTime().getTime()) / 1000;// 除以1000是为了转换成秒
				}
				hour = between / 3600;
				between = between - hour * 3600;
				min = between / 60;
				between = between - min * 60;
				s = between;
				if(sweepClose.getWarnTime()!=null){
					warnTime = (new Date().getTime() - sweepClose.getWarnTime().getTime()) / 1000;// 除以1000是为了转换成秒
				}
				if ((hour > 0 || min >= 5) && (sweepClose.getWarnTime() == null || warnTime / 60 >= 5)) {
					String msg = "";
					msg = hour > 0 ? (msg + hour + "小时") : msg;
					msg = hour > 0 ? (msg + min + "分") : (min > 0 ? (msg + min + "分") : msg);
					msg = min > 0 ? (msg + s + "秒") : (s > 0 ? (msg + s + "秒") : msg);
					sweepCloseVO.setTime(sweepClose.getTime());
					sweepCloseVO.setMsg(msg);
					sweepCloseVO.setIsSend(1);
					sweepClose.setWarnTime(new Date());
				} else {
					sweepCloseVO.setIsSend(0);
				}
				//修改承接单是否开启接单按钮
				businessInfoApi.updateSweepClose(sweepClose);
				sweepCloseVO.setState(0);
				sweepCloseVO.setMsg("商家暂未营业");
				res.setData(sweepCloseVO);
				return res;
			} else {
				
				ShopperExtend shopper = shopperInfoServiceApi.getShopperExtend(storeId);
				String businessTime = "00:00~00:00";
				// 营业开始时间
				String startTime = "00:00";
				// 营业结束时间
				String endTime = "00:00";
				if(shopper!=null){
					businessTime = shopper.getBusinessTime();
				}
				try{
					startTime = businessTime.split("~")[0];
					endTime = businessTime.split("~")[1];
				}catch (Exception e) {
					startTime = "00:00";
					endTime = "00:00";
				}
				String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();// 当前年月日
				String startStr = currDate + " " + startTime + ":00";
				String endStr = currDate + " " + endTime + ":00";
				// 将字符串数据转化为毫秒数
				try {
					Calendar c = Calendar.getInstance();
					c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startStr));
					Long startSec = c.getTimeInMillis();
					c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endStr));
					Long endSec = c.getTimeInMillis();
					if (startSec.equals(endSec)) {
						sweepCloseVO.setState(1);
						sweepCloseVO.setMsg("24小时营业");
						res.setData(sweepCloseVO);
						return res;
					}
					Long nowSec = new Date().getTime();// 当前时间毫秒数
					if (startSec > endSec) {// 跨天 结束时间则要加一天
						if(nowSec > startSec){
							endSec = endSec + new Long(24*60*60*1000);
						}else{
							startSec = startSec - new Long(24*60*60*1000);
						}
					}
					if (nowSec >= startSec && nowSec <= endSec) {
						sweepCloseVO.setState(1);
						sweepCloseVO.setMsg("营业中");
						res.setData(sweepCloseVO);
						return res;
					} else {
						sweepCloseVO.setState(0);
						sweepCloseVO.setMsg("不在营业时间范围内，营业时间为：" + startTime + "-" + endTime);
						res.setData(sweepCloseVO);
						return res;
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("店铺营业时间查询++++++++++++++++++=" + Utils.log4jDetail(e));
				}
			}
		}else{
			sweepCloseVO.setState(0);
			if(Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)){
				sweepCloseVO.setMsg("店铺暂未开启在线订单");
			}else if(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().equals(clientOrderMode)){
                sweepCloseVO.setMsg("店铺暂未开启外卖订单");
            }else{
				sweepCloseVO.setMsg("店铺暂未开启扫码下单");
			}
			res.setData(sweepCloseVO);
		}
		return res;
	}

	@Override
	public Map<String,Object> updateCupboard(OpenCupboardEntryVO openCupboardVO) {
		Map<String,Object> map = new HashMap<String,Object>();
		//获取redis店铺配置信息
		Object config = redisServiece.getObj(openCupboardVO.getStoreId()+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(openCupboardVO.getStoreId());
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		
		RelMachineHardWare machineHard = new RelMachineHardWare();
		machineHard.setStoreId(openCupboardVO.getStoreId());
		machineHard.setType(2);
		machineHard.setThirdMachineBrand("pinyuan");
		//在线订单店铺机器绑定信息
		RelMachineHardWare hardWare = orderServiceApi.getMachineHardWareInfo(machineHard);
		JSONObject json = new JSONObject();
		Map<String, String> nameValuePair = new HashMap<String, String>();
		if(hardWare!=null){
			//获取取餐柜的柜子信息
			CupboardOrderRecord orderRecord = new CupboardOrderRecord();
			orderRecord.setCellId(openCupboardVO.getCellId());
			if(!StringUtils.isEmpty(openCupboardVO.getTakeCode()) && openCupboardVO.getTakeCode().length()>=17){
				orderRecord.setTakeCode(openCupboardVO.getTakeCode());
			}else{
				orderRecord.setOrderNum(openCupboardVO.getOrderNum());
			}
			List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
			if(CollectionUtils.isEmpty(orderRecordList)){
				map.put("msg", "开柜失败该柜子已经完成");
				map.put("success", false);
				return map;
			}
			json.put("orderNum", openCupboardVO.getOrderNum());
			json.put("cellId", openCupboardVO.getCellId());
			//开通kds
			if(shopperConfigExt!=null && new Integer(1).equals(shopperConfigExt.getIsOpenKDS())){
				json.put("orderId", orderRecordList.get(0).getIdentifyingCode());
			}else{
				json.put("orderId", openCupboardVO.getTakeCode());
			}
			json.put("shopId", openCupboardVO.getStoreId());
			nameValuePair.put("method", "ajax/pinyuanOpenCabinetDoorByOrderNum");
			nameValuePair.put("biz_content", json.toJSONString());
		}else{
			json.put("orderNum", openCupboardVO.getOrderNum());
			json.put("takeCode", openCupboardVO.getTakeCode());
			json.put("cellId", openCupboardVO.getCellId());
			json.put("storeId", openCupboardVO.getStoreId());
			nameValuePair.put("method", "iot/takeGoodsByCode");
			nameValuePair.put("biz_content", json.toJSONString());
		}
		CoreResponse<String> result = HttpUtils.doPostForm(openIntelligenceUrl,
					nameValuePair, 60000, 60000, "UTF-8");
		//判断调用接口参数
		logger.info("调用取餐柜柜子接口================"+JSONObject.toJSONString(result)+"\\n"+JSONObject.toJSONString(nameValuePair)+"\\n"+openIntelligenceUrl);
		if(result!=null && !StringUtils.isEmpty(result.getData())){
			JSONObject jo = JSONObject.parseObject(result.getData());
			if(("10000").equals(jo.getString("code"))){
				map.put("msg", "开柜成功");
				map.put("success", true);
			}else{
				map.put("msg", "开柜失败："+jo.getString("msg"));
				map.put("success", false);
			}
		}else{
			map.put("msg", "开柜失败调用开柜接口失败");
			map.put("success", false);
		}
		return map;
	}

	@Override
	public int updateWaimaiByOrderNum(Waimai param) {
		return waimaiServiceApi.updateWaimaiByOrderNum(param);
	}

	@Override
	public Map<String, Object> onlineCupboardNum(Integer storeId, String buyerId) {
		Map<String, Object> map = new HashMap<String,Object>();
		
		WaimaiParam param = new WaimaiParam();
		param.setStoreId(storeId);
		param.setBuyerId(buyerId);
		param.setOrderType(2);
		param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
		param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
		param.setPrepMealStatus(2);
		param.getStatuses().add(Constants.orderStatus.STATUS_ZERO.getValue());
		param.getStatuses().add(Constants.orderStatus.STATUS_ONE.getValue());
		param.getStatuses().add(Constants.orderStatus.STATUS_ELEVEN.getValue());
		param.setStartDate(DateUtils.getBeforeDate(5));
		param.setEndDate(DateUtils.getNowTime());
		//取餐柜待取餐订单数量
		int cupboardNum=0;
		//获取在线订单取餐柜订单
		List<WaimaiExtend> waimaiList = waimaiServiceApi.getOnlineMealOrder(param);
		if(!CollectionUtils.isEmpty(waimaiList)){
			for(WaimaiExtend waimai:waimaiList){
				CupboardOrderRecord orderRecord = new CupboardOrderRecord();
				orderRecord.setOrderNum(waimai.getOrderNum());
				//获取取餐柜订单下的柜子
				List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
				if(!CollectionUtils.isEmpty(orderRecordList)){
					//状态为1
					int statusOne = 0;
					for(CupboardOrderRecord record:orderRecordList){
						//取餐柜订单中 多个餐柜中只要有一个为1待取餐则这个订单为待取餐 
						if (!new Integer(2).equals(waimai.getPrepMealStatus())
								&& new Integer(1).equals(record.getGoodStatus())) {
							statusOne++;
						}
					}
					//如果该取餐柜订单已经完成了就不能再跟改状态
					if (!new Integer(2).equals(waimai.getPrepMealStatus())) {
						// 餐柜个数
						if (statusOne>0) {
							cupboardNum++;
						} 
					}
				}
			}
		}
		map.put("cupboardNum", cupboardNum);
		return map;
	}

	@Override
	public List<WisdomOrderVO> getWisdomOrderBySeq(Integer storeId, String orderSeq,String buyerId) {
		//获取redis店铺配置信息
		Object config = redisServiece.getObj(storeId+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		
		Integer orderSeqInt = Integer.valueOf(orderSeq.replaceAll("^(0+)", ""));
		//根据取餐号获取24小时内的订单
		WaimaiParam param = new WaimaiParam();
		param.setStoreId(storeId);
		param.setOrderSeq(orderSeqInt);
		param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
		param.setStartDate(DateUtils.getBeforeDate(24));
		param.setEndDate(DateUtils.getNowTime());
		param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
		param.setNotStatus(Constants.orderStatus.STATUS_TWO.getValue());
		List<WaimaiExtend> waimaiList = waimaiServiceApi.getOnlineMealOrder(param);
		List<WisdomOrderVO> orderVOList = new ArrayList<WisdomOrderVO>();
		
		//如果开启kds，则订单状态根据菜品状态显示
		if(new Integer(1).equals(shopperConfigExt.getIsOpenKDS()) && !CollectionUtils.isEmpty(waimaiList)){
			for(WaimaiExtend waimaiExtend:waimaiList){
				//堂食落单buyerId不存在
				if(buyerId.equals(waimaiExtend.getBuyerId()) || StringUtils.isEmpty(waimaiExtend.getBuyerId())){
					//开通kds取餐柜订单，查询单个菜品的状态，及根据菜品状态判断订单状态
					waimaiExtend = waimaiExtendGoodsStatus(shopperConfigExt.getIsOpenKDS(),waimaiExtend);
					WisdomOrderVO orderVO = new WisdomOrderVO();
					//订单状态
					orderVO.setPrepMealStatus(waimaiExtend.getPrepMealStatus());
					// 订单号
					orderVO.setOrderNum(waimaiExtend.getOrderNum());
					// 取餐码
					orderVO.setTakeMealCode(waimaiExtend.getTakeMealCode());
					// 取餐号
					orderVO.setOrderSeq(Utils.getOrderSeq(waimaiExtend.getOrderSeq()));
					// 店铺名称
					orderVO.setShopperName(waimaiExtend.getShopName());
					orderVO.setCreateTime(DateUtils.getDateChangeString(waimaiExtend.getCreateTime()));
					orderVOList.add(orderVO);
				}
			}
		}else if(!CollectionUtils.isEmpty(waimaiList)){
			for(WaimaiExtend waimaiExtend:waimaiList){
				//堂食落单buyerId不存在
				if(buyerId.equals(waimaiExtend.getBuyerId()) || StringUtils.isEmpty(waimaiExtend.getBuyerId())){
					//根据取餐号获取24小时前柜子信息
					CupboardOrderRecord orderRecord =new CupboardOrderRecord();
					if(waimaiExtend!=null && !StringUtils.isEmpty(waimaiExtend.getTakeMealCode()) && waimaiExtend.getTakeMealCode().length()>=17){
						orderRecord.setTakeCode(waimaiExtend.getTakeMealCode());
					}else{
						orderRecord.setTakeMealNum(orderSeq);
					}
					orderRecord.setStoreId(storeId);
					orderRecord.setCreateTime(CalendarUtil.formatDateByString(DateUtils.getBeforeDate(24)));
					List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
					WisdomOrderVO orderVO = new WisdomOrderVO();
					if (!CollectionUtils.isEmpty(orderRecordList)) {
						// 状态为2
						int statusTwo = 0;
						// 状态为0
						int statusZero = 0;
						for (CupboardOrderRecord record : orderRecordList) {
							// 取餐柜订单中 多个餐柜中只要有一个为1待取餐则这个订单为待取餐
							if (new Integer(1).equals(record.getGoodStatus())) {
								// 订单备餐状态
								orderVO.setPrepMealStatus(waimaiExtend.getPrepMealStatus());
								break;
							}
							// 餐柜的状态为2已取餐
							if (new Integer(2).equals(record.getGoodStatus())) {
								statusTwo++;
							}
							// 餐柜的状态为0制作中
							if (new Integer(0).equals(record.getGoodStatus())) {
								statusZero++;
							}
						}
						if(!new Integer(2).equals(waimaiExtend.getPrepMealStatus())) {
							// 餐柜个数
							int orderSize = orderRecordList.size();
							// 全部都是状态为0的柜台
							if (orderSize == statusZero) {
								orderVO.setPrepMealStatus(0);
								// 状态柜台为2的
							} else if (statusTwo == orderSize || ((statusTwo + statusZero) == orderSize)) {
								orderVO.setPrepMealStatus(2);
							}else{
								orderVO.setPrepMealStatus(1);
							}
						}
					}else{
						orderVO.setPrepMealStatus(0);
					}
					// 订单号
					orderVO.setOrderNum(waimaiExtend.getOrderNum());
					// 取餐码
					orderVO.setTakeMealCode(waimaiExtend.getTakeMealCode());
					// 取餐号
					orderVO.setOrderSeq(Utils.getOrderSeq(waimaiExtend.getOrderSeq()));
					// 店铺名称
					orderVO.setShopperName(waimaiExtend.getShopName());
					orderVO.setCreateTime(DateUtils.getDateChangeString(waimaiExtend.getCreateTime()));
					orderVOList.add(orderVO);
				}
			}
		}
		return orderVOList;
	}

    /**
     *
     * @param isOpenInvioce
     * @param waimaiVO
     * @return
     */
    public WaimaiVO waimaiVOInvoice(Integer isOpenInvioce,WaimaiVO waimaiVO, Date date, Integer storeId, List<InvoiceServiceInfo> invoiceServiceInfo){
        if(new Integer(0).equals(isOpenInvioce) || Utils.isEmpty(invoiceServiceInfo)){
            return waimaiVO;
        }
        boolean flag = true;
        // 遍历开发票服务信息不支持开发票的支付方式
        for(InvoiceServiceInfo serviceInfo : invoiceServiceInfo){
            if(serviceInfo.getPayModel() != null && waimaiVO.getPayModel().equals(serviceInfo.getPayModel())){
                flag = false;
                break;
            }
        }
        // 查询当前订单是否已经开过发票
        boolean isOpenInvoice = orderServiceApi.isOpenInvoice(storeId, waimaiVO.getOrderNum());
        logger.info("当前是否已开通电子发票isOpenInvoice="+isOpenInvoice+"+++flag="+flag+"+++isOpenInvoice="+!isOpenInvoice);
        if(flag==true && isOpenInvoice==false && new Integer(1).equals(waimaiVO.getPayStatus()) && DateUtils.dateFormat(waimaiVO.getCreateTime()).getTime() <= date.getTime()
                && date.getTime() <= DateUtils.getDateForXAfterMonth(DateUtils.dateFormat(waimaiVO.getCreateTime()), 2).getTime()){
            waimaiVO.setIsOpenInvoice(true);
        }
        return waimaiVO;
    }
	@Override
	public List<WisdomOrderVO> getWisdomOrderInfo(Integer storeId, String buyerId) {
		//获取redis店铺配置信息
		Object config = redisServiece.getObj(storeId+"_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		
		List<WisdomOrderVO> orderVOList = null;
		WaimaiParam param = new WaimaiParam();
		param.setBuyerId(buyerId);
		param.setStoreId(storeId);
		param.setPayStatus(Constants.payStatus.PAYSTATUS_ONE.getValue());
		param.setOrderType(2);
		param.setNotStatus(Constants.orderStatus.STATUS_TWO.getValue());
		param.setStartDate(DateUtils.getBeforeDate(24));
		param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
		param.setEndDate(DateUtils.getNowTime());
		//获取取餐柜24小时内订单信息
		List<WaimaiExtend> waimaiList = waimaiServiceApi.getOnlineMealOrder(param);
		//开通KDS的取餐柜/订单状态根据菜品状态显示
		if(new Integer(1).equals(shopperConfigExt.getIsOpenKDS()) && !CollectionUtils.isEmpty(waimaiList)){
			orderVOList = new ArrayList<WisdomOrderVO>();
			for(WaimaiExtend waimai:waimaiList){
				//开通kds取餐柜订单，查询单个菜品的状态，及根据菜品状态判断订单状态
				waimai = waimaiExtendGoodsStatus(shopperConfigExt.getIsOpenKDS(),waimai);
				WisdomOrderVO orderVO = new WisdomOrderVO();
				orderVO.setOrderNum(waimai.getOrderNum());
				orderVO.setPrepMealStatus(waimai.getPrepMealStatus());
				orderVO.setShopperName(waimai.getShopName());
				orderVO.setTakeMealCode(waimai.getTakeMealCode());
				orderVO.setOrderSeq(Utils.getOrderSeq(waimai.getOrderSeq()));
				orderVO.setCreateTime(DateUtils.getDateChangeString(waimai.getCreateTime()));
				orderVOList.add(orderVO);
			}
		}else if(!CollectionUtils.isEmpty(waimaiList)){
			orderVOList = new ArrayList<WisdomOrderVO>();
			for(WaimaiExtend waimai:waimaiList){
				CupboardOrderRecord orderRecord = new CupboardOrderRecord();
				if(!StringUtils.isEmpty(waimai.getTakeMealCode()) && waimai.getTakeMealCode().length()>=17){
					orderRecord.setTakeCode(waimai.getTakeMealCode());
					orderRecord.setStoreId(waimai.getShopId());
				}else{
					orderRecord.setOrderNum(waimai.getOrderNum());
				}
				//获取取餐柜柜子信息
				List<CupboardOrderRecord> orderRecordList = orderServiceApi.getOnlineMealRecordByNum(orderRecord);
				if(!CollectionUtils.isEmpty(orderRecordList)){
					//状态为2
					int statusTwo = 0;
					//状态为0
					int statusZero = 0;
					for(CupboardOrderRecord record:orderRecordList){
						//取餐柜订单中 多个餐柜中只要有一个为1待取餐则这个订单为待取餐 
						if (!new Integer(2).equals(waimai.getPrepMealStatus())
								&& new Integer(1).equals(record.getGoodStatus())) {
							waimai.setPrepMealStatus(1);
						}
						//餐柜的状态为2已取餐
						if(new Integer(2).equals(record.getGoodStatus())){
							statusTwo++;
						}
						//餐柜的状态为0制作中
						if(new Integer(0).equals(record.getGoodStatus())){
							statusZero++;
						}
					}
					//如果该取餐柜订单已经完成了就不能再跟改状态
					if (!new Integer(2).equals(waimai.getPrepMealStatus())) {
						// 餐柜个数
						int orderSize = orderRecordList.size();
						// 全部都是状态为0的柜台
						if (orderSize == statusZero) {
							waimai.setPrepMealStatus(0);
							// 状态柜台为2的
						} else if (statusTwo == orderSize || ((statusTwo + statusZero) == orderSize)) {
							waimai.setPrepMealStatus(2);
						}
					}
					waimai.setTakeMealCode(orderRecordList.get(0).getTakeCode());
				}else{
					waimai.setPrepMealStatus(0);
				}
				WisdomOrderVO orderVO = new WisdomOrderVO();
				orderVO.setOrderNum(waimai.getOrderNum());
				orderVO.setPrepMealStatus(waimai.getPrepMealStatus());
				orderVO.setShopperName(waimai.getShopName());
				orderVO.setTakeMealCode(waimai.getTakeMealCode());
				orderVO.setOrderSeq(Utils.getOrderSeq(waimai.getOrderSeq()));
				orderVO.setCreateTime(DateUtils.getDateChangeString(waimai.getCreateTime()));
				orderVOList.add(orderVO);
			}
		}
		return orderVOList;
	}
	
	@Override
	public CoreResponse<Map<String,Object>> getOrderLockInfo(Integer storeId, String orderNum) {
		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		// 查询订单状态
		WaimaiExtend waimai = getWaimaiDeatilsByOrderNum(orderNum);
		if (waimai == null) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			return res;
		} 
		// 订单锁状态
		Integer lockStatus = null != waimai.getLockStatus() ? waimai.getLockStatus() : null ;
		// 订单锁时间
		Date lockTime =  null != waimai.getLockTime() ? (Date)waimai.getLockTime() : null ;
		// 支付状态
		Integer payStatus = null != waimai.getPayStatus() ? waimai.getPayStatus() : null ;
		Map<String,Object> map = new HashMap<String,Object>();
		if (new Integer(1).equals(payStatus)) {
			map.put("endPay", 1);
			res.setData(map);
			res.setSubMsg("订单已经被支付");
			return res;
		}
		// 获取系统时间 减去 订单上锁时间
		Long sec = 0L;
		if (lockTime != null) {
			sec = System.currentTimeMillis() - lockTime.getTime();
		}
		// 如果订单上支付锁或者预结锁了 则不能支付和加菜
		if(new Integer(1).equals(lockStatus)){
			map.put("beingPay", 1);
			res.setData(map);
			res.setSubMsg("订单正在支付");
			return res;
		}
		// 如果订单上订单锁则不能支付和加菜
		if (new Integer(2).equals(lockStatus)) {
			map.put("orderLock", 1);
			res.setData(map);
			res.setSubMsg("订单正在加菜");
			return res;
		}
		// 如果订单上预结锁了 则不能加菜
		if(new Integer(3).equals(lockStatus)){
			map.put("endPay", 1);
			res.setData(map);
			res.setSubMsg("订单正在支付");
		}
		// 如果订单上支付锁了 则不能支付和加菜
		if(new Integer(4).equals(lockStatus) && sec < Long.valueOf(15000) && sec > new Long(0)){
			map.put("beingPay", 1);
			res.setData(map);
			res.setSubMsg("订单正在支付");
			return res;
		}
		res.setSubMsg("订单可以支付");
		return res;
	}

	/**
	 * 获取会员优惠券列表
	 */
	@Override
	public CoreResponse<WaimaiVO> getCouponList(Integer storeId, String tableName, String buyerId, String takeMealCode,
			String wisdomFlag, Integer clientOrderMode) {
		CoreResponse<WaimaiVO> response = new CoreResponse<WaimaiVO>();
		return response;
	}

	/**
	 * 获取当天未核销的订单
	 */
	@Override
	public CoreResponse<List<WaimaiVO>> getTodayNoHexiaoOrder(Integer storeId, String buyerId,Long outerSupportId) {
		 CoreResponse<List<WaimaiVO>> res = new  CoreResponse<List<WaimaiVO>>();
		//查询未核销订单
		List<WaimaiExtend> waimaiList = getTodayOrderHexiaoOrDelivery(storeId,buyerId,outerSupportId);
		if(Utils.isEmpty(waimaiList)){
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setMsg("暂无未核销订单");
			return res;
		}
		List<WaimaiVO> waimaiVOList= new ArrayList<WaimaiVO>();
		for (WaimaiExtend waimai : waimaiList) {
			String reachTime = waimai.getReachTime();
			String dateStr = reachTime.split(" ")[0];
			String startTimeStr = reachTime.split(" ")[1].split("-")[0];
			String endTimeStr = reachTime.split(" ")[1].split("-")[1];
			ReserveBasicInfo reserveBasicInfo = shopperInfoServiceApi.getReserveBasicInfoByTime(waimai.getShopperId(), storeId, reachTime.split(" ")[1]);
			Double beforeHour = ((reserveBasicInfo==null || reserveBasicInfo.getBeforeHour()==null)?1.0:reserveBasicInfo.getBeforeHour())*60;
			Double afterHour = ((reserveBasicInfo==null || reserveBasicInfo.getAfterHour()==null)?1.0:reserveBasicInfo.getAfterHour())*60;

			try {
				Date reachStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr+" "+startTimeStr+":00");
				long time=(reachStartTime.getTime()/1000)-60*(beforeHour.longValue());
				reachStartTime.setTime(time*1000);


				Date reachEndTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr+" "+endTimeStr+":00");
				time=(reachEndTime.getTime()/1000)+60*(afterHour.longValue());
				reachEndTime.setTime(time*1000);
				Date now = new Date();
				if(reachStartTime.getTime()<now.getTime() && reachEndTime.getTime()>now.getTime()) {
					WaimaiVO waimaiVO = new WaimaiVO();
					BeanUtils.copyProperties(waimai, waimaiVO);
					waimaiVOList.add(waimaiVO);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		res.setData(waimaiVOList);
		res.setStatusInfo(StatusInfo.SUCCESS);
		res.setMsg("查询成功");
		return res;
	}

	private List<WaimaiExtend> getTodayOrderHexiaoOrDelivery(Integer storeId, String buyerId,Long outSupportId) {
		WaimaiParam param = new WaimaiParam();
		param.setBuyerId(buyerId);
		param.setStoreId(storeId);
		param.setStartDate(CalendarUtil.getDate4Day(new Date(),1));
		param.setEndDate(CalendarUtil.getCurrentTime());
		param.setOrderType(4);
		// 在线订单
		if(outSupportId == 4L || outSupportId == 81L){
//			param.setOutSupportId(Constants.orderOutSupportId.ONLINE_ORDER.getValue());
            param.setOutSupportId(outSupportId);
			param.setIsHexiao(0);
			param.setStatus(Constants.orderStatus.STATUS_ONE.getValue());
			param.setHexiaoType(0);
		}else{
			param.setOutSupportId(Constants.orderOutSupportId.SCAN_ORDER.getValue());
			param.setDeliveryStatus(0);
			param.setStatus(Constants.orderStatus.STATUS_ELEVEN.getValue());
		}
		List<WaimaiExtend> waimai = waimaiServiceApi.getTodayOrderHexiaoOrDelivery(param);
		return waimai;
	}

	@Override
	public CoreResponse<List<WaimaiVO>> getTodayNoDeliveryOrder(Integer storeId, String buyerId,Long outerSupportId) {
		CoreResponse<List<WaimaiVO>> res = new  CoreResponse<List<WaimaiVO>>();
			//查询未核销订单
		List<WaimaiExtend> waimaiList = getTodayOrderHexiaoOrDelivery(storeId,buyerId,outerSupportId);
		List<WaimaiVO> waimaiVOList= new ArrayList<WaimaiVO>();
		if(Utils.isEmpty(waimaiList) || waimaiList.size()<1){
			res.setStatusInfo(StatusInfo.SUCCESS);
			res.setMsg("暂无未配送订单");
			return res;
		}
		for(WaimaiExtend waimai : waimaiList){
			WaimaiVO waimaiVO = new WaimaiVO();
			BeanUtils.copyProperties(waimai, waimaiVO);
			waimaiVOList.add(waimaiVO);
		}
		res.setData(waimaiVOList);
		res.setStatusInfo(StatusInfo.SUCCESS);
		res.setMsg("查询成功");
		return res;
	}

	@Override
	public List<Waimai> getMyUnPayOrder(Integer storeId, String tableName, String buyerId) {
		return waimaiServiceApi.getMyUnPayOrder( storeId,  tableName,  buyerId);
	}

	@Override
	public void deleteUnpayHistoryOrderById(Long id) {
		waimaiServiceApi.deleteUnpayHistoryOrderById(id);

	}

    @Override
    public CoreResponse<Object> getDistributionFee(DistributionFeeVo distributionFeeVo) {
        CoreResponse<Object> res = new CoreResponse<>();
        Integer storeId = distributionFeeVo.getStoreId();
        //最大配送距离
        Double maxDistance = distributionFeeVo.getMaxDistance();
        //用户经纬度
        Double userLng = distributionFeeVo.getUserLng();
        Double userLat = distributionFeeVo.getUserLat();
        //店铺经纬度
        Double shopLng;
        Double shopLat;
        TakeOutConfig takeOutConfig = shopperInfoServiceApi.getTakeOutConfigByStoreId(storeId);
        if(takeOutConfig == null){
            res.setCode(StatusInfo.NORESOURCE.getCode());
            res.setSubMsg("商家无外卖配置，计算配送费失败！");
            return res;
        }
        //根据商家外卖配送方式，取商家经纬度。如果商家设置自配送，则取商家后台设置的经纬度；如果商家设置了第三方配送，则取第三方配送返回的经纬度。
        if (new Integer(0).equals(takeOutConfig.getTakeOutMethod())
                || new Integer(4).equals(takeOutConfig.getTakeOutMethod())) {
            ShopperExtend shopperExtend = shopperInfoServiceApi.getShopperExtend(storeId);
            shopLng = shopperExtend.getY();
            shopLat = shopperExtend.getX();
        } else {
            Map<String, Object> shopMap = shopperInfoServiceApi.getShopLatAndLng(storeId, takeOutConfig.getTakeOutMethod());
            if (null == shopMap || null == shopMap.get("lng") || null == shopMap.get("lat") ||
                    Utils.isEmpty(shopMap.get("lng").toString()) || Utils.isEmpty(shopMap.get("lat").toString())) {
                res.setSubMsg("数据异常");
                res.setCode(StatusInfo.NORESOURCE.getCode());
                return res;
            } else {
                shopLng = Double.valueOf(shopMap.get("lng").toString());
                shopLat = Double.valueOf(shopMap.get("lat").toString());
            }
        }
        if (null == shopLng || null == shopLat) {
            res.setSubMsg("获取商家坐标失败，计算失败");
            res.setCode(StatusInfo.NORESOURCE.getCode());
            return res;
        }
        //只查询是否在配送范围
        Integer rangeOnly = distributionFeeVo.getRangeOnly();
        //有商家经纬度，并且有商家最大配送范围，并且是只查询范围时，则直接使用，不需要再去查询
        Double distance = null; //商家与顾客之间的地址距离
        HashMap<Object, Object> resultMap = new HashMap<>();
        if(maxDistance != null && new Integer(1).equals(rangeOnly)){
            distance = DeliveryPayUtils.getDistance(userLng, userLat, shopLng, shopLat);
            //如果只查询是否在配送范围内
            resultMap.put("distance", distance);
            resultMap.put("shopLng", shopLng);
            resultMap.put("shopLat", shopLat);
            res.setData(resultMap);
            return res;
        }else{
            logger.info("获取商家定位信息：" + shopLng + "," + shopLat);
            if (shopLng < -180 || shopLng > 180 || shopLat < -90 || shopLat > 90) {
                res.setSubMsg("获取商家坐标异常，计算失败");
                res.setCode(StatusInfo.NORESOURCE.getCode());
                return res;
            }
            distance = DeliveryPayUtils.getDistance(userLng, userLat, shopLng, shopLat);
            logger.info("计算配送距离：" + distance);
            //配送费计算方式
            TakeOutBilling takeOutBilling = shopperInfoServiceApi.findTakeOutBillingList(storeId,takeOutConfig.getId());
            if(takeOutBilling == null){
                res.setSubMsg("获取商家配送费计费方式，计算配送费失败！");
                res.setCode(StatusInfo.NORESOURCE.getCode());
                return res;
            }
            Map<String, Object> result = getDeliveryPay(takeOutConfig, takeOutBilling, distance);
            if (result.get("success").toString().equals("true")) {
                Double deliveryPay = Double.valueOf(result.get("deliveryPay").toString());
                logger.info("计算配送费成功：distance:" + distance + ",deliveryPay:" + deliveryPay + ",maxDistance:" + takeOutConfig.getMaxTakeOutDistance() +
                        ",miniDeliveryAmount:" + takeOutConfig.getMinimumDeliveryAmount());
                resultMap.put("distance", distance);
                resultMap.put("deliveryPay", deliveryPay);
                resultMap.put("maxDistance", takeOutConfig.getMaxTakeOutDistance());
                resultMap.put("shopLng", shopLng);
                resultMap.put("shopLat", shopLat);
                resultMap.put("miniDeliveryAmount", takeOutConfig.getMinimumDeliveryAmount());
                res.setMsg("计算配送费成功");
                res.setCode(StatusInfo.SUCCESS.getCode());
                res.setData(resultMap);
                return res;
            } else {
                if (result.get("code").toString().equals("40001")) {
                    logger.info("计算配送费失败，超出商家配送范围：distance:" + distance + ",maxDistance:" + takeOutConfig.getMaxTakeOutDistance() +
                            ",miniDeliveryAmount:" + takeOutConfig.getMinimumDeliveryAmount() + ",outRange:" + true);
                    resultMap.put("distance", distance);
                    resultMap.put("maxDistance", takeOutConfig.getMaxTakeOutDistance());
                    resultMap.put("outRange", true);
                    resultMap.put("shopLng", shopLng);
                    resultMap.put("shopLat", shopLat);
                    resultMap.put("miniDeliveryAmount", takeOutConfig.getMinimumDeliveryAmount());
                    res.setMsg("超出商家配送范围，计算配送费失败！");
                    res.setCode("40007");
                    return res;
                } else {
                    logger.info("计算配送费失败，计算配送费异常：distance:" + distance + ",maxDistance:" + takeOutConfig.getMaxTakeOutDistance() +
                            ",miniDeliveryAmount:" + takeOutConfig.getMinimumDeliveryAmount());
                    resultMap.put("distance", distance);
                    resultMap.put("miniDeliveryAmount", takeOutConfig.getMinimumDeliveryAmount());
                    res.setMsg("计算配送费异常！");
                    res.setCode("40008");
                    return res;
                }
            }
        }
    }

    @Override
    public CoreResponse<Object> getWaimaiBusinessInfo(Integer storeId) {
        CoreResponse<Object> res = new CoreResponse<>();
        HashMap<String, Object> resultMap = new HashMap<>();
        TakeOutConfig takeOutConfig = shopperInfoServiceApi.getTakeOutConfigByStoreId(storeId);
        if(takeOutConfig == null){
            resultMap.put("msg", "店铺无外卖配置信息");
            res.setCode(StatusInfo.NORESOURCE.getCode());
            res.setMsg("店铺无外卖配置信息");
            return res;
        }
        if (new Integer(1).equals( takeOutConfig.getTakeOutOpen())) {
            //查询外卖时段
            String businessTime = shopperInfoServiceApi.getWaimaiBusinessInfo(storeId,takeOutConfig.getTakeOutPeriodType());
//            ShopBusinessInfoVo shopBusinessInfo = shopperInfoServiceApi.getShopBusinessInfo(storeId);
//            String businessTime = shopBusinessInfo.getBusinessTime();
            logger.info("获取外卖时段：{}",businessTime);
            if(Utils.isEmpty(businessTime)){
                resultMap.put("time",new String[]{});
            }else{
                businessTime = businessTime.replace("~", "-");
                resultMap.put("time",businessTime.split(","));
            }

            //获取时间
//            String businessWeek = shopBusinessInfo.getBusinessWeek();
//            if(!Utils.isEmpty(businessWeek)){
//                String[] businessWeeks = businessWeek.split(",");
//                int dayOfWeek = DateUtils.getDayofweek();
//                for (int i = 0; i < businessWeeks.length;i++) {
//                    if(Integer.parseInt(businessWeeks[i]) == dayOfWeek){
//
//                    }
//                }
//            }
            HashMap<String, String> timeMap = new HashMap<>(3);
            timeMap.put(Constants.WaimaiOrderTime.YESTERDAY.getValue(),Constants.WaimaiOrderTime.YESTERDAY.getName());
            timeMap.put(Constants.WaimaiOrderTime.TODAY.getValue(),Constants.WaimaiOrderTime.TODAY.getName());
            timeMap.put(Constants.WaimaiOrderTime.TOMORROW.getValue(),Constants.WaimaiOrderTime.TOMORROW.getName());
            resultMap.put("date",timeMap);
        } else {
            resultMap.put("msg", "商家已关闭外卖配送");
            res.setCode(StatusInfo.SUCCESS.getCode());
            res.setMsg("商家已关闭外卖配送");
        }
        res.setData(resultMap);
        return res;
    }


    /**
     *<pre>
     * 说    明: 外卖拣货订单
     * 涉及版本:
     * 创 建 者: YangYangjun
     * 日    期: 2020-03-07 14:34
     *</pre>
     **/
    @Override
    public CoreResponse<SaveWaimaiVO> createWaimaiPickingOrder(CreateWaimaiEntryDto createWaimai) {
        String waimaiType = createWaimai.getWaimaiType();
        //外卖类型0-配送外卖，1-自提外卖
        CoreResponse<SaveWaimaiVO> res = new CoreResponse<>();
        if(CommonConstants.WaimaiType.DISTRIBUTE.getCode().equals(waimaiType)){
            if(createWaimai.getReceiverAddress() == null
                    || createWaimai.getReceiverLat() == null
                    || createWaimai.getReceiverLng() == null
                    || createWaimai.getReceiverName() == null
                    || createWaimai.getReceiverSex() == null
                    || createWaimai.getReceiverTel() == null
                    || createWaimai.getDeliveryPay() == null
                    || createWaimai.getDeliveryPay() < 0
                    || createWaimai.getPeopleNumber() == null
                    || createWaimai.getPeopleNumber() < 0){
                res.setCode(StatusInfo.FORBIDDEN.getCode());
                res.setSubMsg("缺少参数");
                return res;
            }
        }else if(createWaimai.getReachTime() == null
                || createWaimai.getPeopleNumber() == null
                || createWaimai.getPeopleNumber() < 0){
            res.setCode(StatusInfo.FORBIDDEN.getCode());
            res.setSubMsg("缺少参数");
            return res;
        }
        String endDeliveryTime = createWaimai.getEndDeliveryTime();
        String startDeliveryTime = createWaimai.getStartDeliveryTime();
        String reachTime = createWaimai.getReachTime();

        //yyyy-MM-dd
        //HH:mm
        if(!Utils.isEmpty(endDeliveryTime) && !Utils.isEmpty(startDeliveryTime) && !Utils.isEmpty(reachTime)){
            if(!DateUtils.matchDateStyle(endDeliveryTime,DateUtils.HHMM)
                || !DateUtils.matchDateStyle(startDeliveryTime,DateUtils.HHMM)
                || !DateUtils.matchDateStyle(reachTime,DateUtils.YYYYMMDD)){
                res.setCode(StatusInfo.FORBIDDEN.getCode());
                res.setSubMsg("配送日期格式有误");
                return res;
            }
        } else if(!Utils.isEmpty(reachTime)){// yyyy-MM-dd HH:mm
            if(!DateUtils.matchDateStyle(reachTime,DateUtils.YYYYMMDD_HHMM)){
                res.setCode(StatusInfo.FORBIDDEN.getCode());
                res.setSubMsg("自提日期格式有误");
                return res;
            }
        }

        //获取获取商家配置信息
        Object config = redisServiece.getObj(createWaimai.getShopId()+"_shopperConfig");
        ShopperConfigExtend shopperConfigExt = null;
        if (config == null) {
            // 查询店铺所有配置
            Map<String, Object> shopperConfig = shopperInfoServiceApi.getShopperAllConfig(Integer.valueOf(createWaimai.getStoreId()));
            // map转成对象
            shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopperConfig);
        } else {
            shopperConfigExt = (ShopperConfigExtend) config;
        }

        Integer storeId = createWaimai.getStoreId();
        //检查外卖配置
        TakeOutConfig takeOutConfig = shopperInfoServiceApi.getTakeOutConfigByStoreId(storeId);
        if(takeOutConfig == null){
            res.setCode(StatusInfo.FORBIDDEN.getCode());
            res.setSubMsg("创建订单失败,商品暂无外卖配置");
            return res;
        }

        String buyerId = createWaimai.getBuyerId();
        //获取商户信息
        ShopperAndParent shopper = shopperInfoServiceApi.getShopperAndParent(createWaimai.getStoreId());
        if(shopper == null){
            res.setCode(StatusInfo.NORESOURCE.getCode());
            res.setSubMsg("获取门店信息失败");
            return res;
        }
        ThirdUserInfo thirdUserInfo = shopperInfoServiceApi.getThirdUserInfo(buyerId, createWaimai.getAuthMode());
        if (Utils.isEmpty(shopper.getMinLogo())) {
        	shopper.setMinLogo(shopper.getParentInfo().getMinLogo());
        }
        //获取购物车商品信息
        List<GoodsCartAndDetail> goodsCartList = shopCartService.getShopCart(storeId, null, buyerId, Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue(), null, null);
        if(CollectionUtils.isEmpty(goodsCartList)){
            res.setCode(StatusInfo.NORESOURCE.getCode());
            res.setSubMsg("创建订单失败,购物车为空");
            return res;
        }

//        double totalPrice = 0D;
//        double totalOriginalPrice = 0D;
//        for (GoodsCartAndDetail gc : goodsCartList) {
//            totalPrice = Arith.add(totalPrice, Arith.mul(gc.getBuyPrice(),gc.getBuyCount()));
//            totalOriginalPrice = Arith.add(totalOriginalPrice, Arith.mul(Utils.isEmpty(gc.getCouponCode()) ? gc.getOriginalPrice() : gc.getBuyPrice(),gc.getBuyCount()));
//        }
        //获取优惠后价格
//        totalPrice = shopCartService.calcPromotionPriceByGoodsCart(totalPrice, goodsCartList, createWaimai, shopper,shopperConfigExt);

        boolean flag = redisServiece.setInxExp(
                "createWaimai_" + createWaimai.getStoreId() + "_" + createWaimai.getBuyerId(), System.currentTimeMillis(),
                5L, TimeUnit.SECONDS);
        if(!flag ){
            //如果key值存在，则判断是否在3s内，大于3s则继续下单且重新set/key值
            Object time = redisServiece.getObj("createWaimai_"+createWaimai.getStoreId()+"_"+createWaimai.getBuyerId());
            if(time!=null){
                Long currentTime = Long.valueOf(String.valueOf(time));
                if ((System.currentTimeMillis() - currentTime) < 5000) {
                    res.setCode(StatusInfo.NORESOURCE.getCode());
                    res.setSubMsg("订单已被创建");
                    return res;
                }else{
                    redisServiece.remove("createWaimai_" + createWaimai.getStoreId() + "_" + createWaimai.getBuyerId());
                    redisServiece.setInxExp(
                            "createWaimai_" + createWaimai.getStoreId() + "_" + createWaimai.getBuyerId(), System.currentTimeMillis(),
                            5L, TimeUnit.SECONDS);
                }
            }
        }
        //查询外卖订单信息
        WaimaiParam waimaiParam = new WaimaiParam();
        waimaiParam.setBuyerId(buyerId);
        waimaiParam.setStoreId(storeId);
        Waimai waimai= waimaiServiceApi.getWaimaiByBuyerId(waimaiParam);

        //如果存在未支付订单直接取消
        if(waimai!=null && new Integer(0).equals(waimai.getPayStatus())){
            waimai.setOrderStatus(12);
            waimaiServiceApi.updateWaimai(waimai);
        }
        SaveWaimaiVO saveWaimai = new SaveWaimaiVO();

        //创建外卖订单
        WaimaiExtend waimaiInfo = createPickUpWaimai(shopper, goodsCartList, createWaimai, thirdUserInfo, shopperConfigExt);
        //检测起送
        Double minimumDeliveryAmount = takeOutConfig.getMinimumDeliveryAmount();
        if(minimumDeliveryAmount != null && waimaiInfo.getTotalPrice() < minimumDeliveryAmount){
            logger.info("minimumDeliveryAmount="+minimumDeliveryAmount+",totalPrice="+waimaiInfo.getTotalPrice());
            //少于起送价格
            res.setCode(StatusInfo.FORBIDDEN.getCode());
            res.setSubMsg("下单失败,起送价："+minimumDeliveryAmount+"元");
            return res;
        }
        waimaiServiceApi.saveWaimai(waimaiInfo, shopperConfigExt,createWaimai);
        //保存订单操作信息
        waimaiServiceApi.saveWaimaiOperateRelated(waimaiInfo, thirdUserInfo, CommonConstants.WaimaiOperateTimeType.ORDER.getValue());
        res.setSubMsg("订单创建成功");
        saveWaimai.setOrderNum(waimaiInfo.getOrderNum());
        saveWaimai.setReachTime(createWaimai.getReachTime());
        saveWaimai.setFlag(1);
        saveWaimai.setIsOut(1);
        saveWaimai.setOrderStatus(waimaiInfo.getOrderStatus());
        res.setData(saveWaimai);
        return res;
    }

    //创建外卖订单
    private WaimaiExtend createPickUpWaimai(ShopperAndParent shopper, List<GoodsCartAndDetail> goodsCartList,CreateWaimaiEntryDto createWaimaiEntryDto,ThirdUserInfo thirdUserInfo,ShopperConfigExtend shopperConfigExt){
        //创建订单对象
        WaimaiExtend waimaiInfo = new WaimaiExtend();
        waimaiInfo.setShopperId(shopper.getParentId());
        waimaiInfo.setShopperName(shopper.getParentInfo().getNick());
        waimaiInfo.setShopName(shopper.getNick());
        waimaiInfo.setShopAddress(shopper.getAddress());
        waimaiInfo.setShopContactPhone(shopper.getContactPhone());
        if (shopper.getMinLogo() != null) {
            waimaiInfo.setShopLogo(shopper.getMinLogo());
        } else {
            waimaiInfo.setShopLogo("/res/css/custom/shop_min.png");
        }
        waimaiInfo.setShopId(shopper.getId());
        waimaiInfo.setShopperId(shopper.getParentId());
        waimaiInfo.setShopperName(shopper.getParentInfo().getNick());
        waimaiInfo.setShopName(shopper.getNick());
        waimaiInfo.setShopAddress(shopper.getAddress());
        waimaiInfo.setBuyerId(createWaimaiEntryDto.getBuyerId());
        waimaiInfo.setUid(createWaimaiEntryDto.getUid());
        waimaiInfo.setIsHexiao(0);
        waimaiInfo.setHexiaoType(0);
        waimaiInfo.setPayplatformPromotionFee(0D);
        waimaiInfo.setThirdPromotionFee(0D);
        waimaiInfo.setCreateTime(new Date());
        waimaiInfo.setOrderNum(Utils.createOrderNum(createWaimaiEntryDto.getStoreId()));
        //收货地址经度
        waimaiInfo.setReceiverLng(createWaimaiEntryDto.getReceiverLng());
        //收货地址纬度
        waimaiInfo.setReceiverLat(createWaimaiEntryDto.getReceiverLat());
        //配送费
        double deliveryPay = createWaimaiEntryDto.getDeliveryPay()==null?0.0:createWaimaiEntryDto.getDeliveryPay();
        waimaiInfo.setDeliveryPay(deliveryPay);
        //配送状态
        waimaiInfo.setDeliveryStatus(0);
        //配送方式
        waimaiInfo.setTakeOutMethod(createWaimaiEntryDto.getDeliveryType());
        //收货人名称
        waimaiInfo.setReceiverName(createWaimaiEntryDto.getReceiverName());
        //收货人性别
        waimaiInfo.setReceiverSex(createWaimaiEntryDto.getReceiverSex());
        //收货人电话
        waimaiInfo.setBuyerMobile(createWaimaiEntryDto.getReceiverTel());
        //收货人详细地址
        waimaiInfo.setAddress(createWaimaiEntryDto.getReceiverAddress());
        //用户昵称
        waimaiInfo.setBuyNick(createWaimaiEntryDto.getBuyerNick()==null?"吃货":createWaimaiEntryDto.getBuyerNick());
        //获取口碑绑定店铺id
        String koubeiShopId = shopperInfoServiceApi.findAlipayStoreIdByShopper(shopper.getId());
        if(!Utils.isEmpty(koubeiShopId)){
            waimaiInfo.setKoubeiShopid(koubeiShopId);
        }
        waimaiInfo.setIsDelete(0);
        //1:预下单 无桌台
        waimaiInfo.setOrderType(1);
        if(shopperConfigExt.getIsOpenPickUp() == null || !new Integer(0).equals(shopperConfigExt.getIsOpenPickUp())){
            waimaiInfo.setPurchStatus(1);//待拣货
        }
        waimaiInfo.setOrderStatus(Constants.orderStatus.STATUS_MINUSONE.getValue());//待确认初始化状态
        waimaiInfo.setOuterSupportId(Long.parseLong(Constants.clientOrderMode.WAIMAI_ORDER_MODE.getValue().toString()));
        waimaiInfo.setPayStatus(0);
        waimaiInfo.setIsPrint(0);
        //订单备注
        waimaiInfo.setNote(createWaimaiEntryDto.getNote());
        //waimaiInfo.setPeopleNumber(0);
        //外卖没有选择人数，默认为1，方便计算餐盒等费用
        waimaiInfo.setPeopleNumber(createWaimaiEntryDto.getPeopleNumber() == null ? 1 : createWaimaiEntryDto.getPeopleNumber());
//        waimaiInfo.setPayModel(10);
        //外卖全部打包
        waimaiInfo.setIsOut(1);
        //是否连锁
        Object isChainStore = shopperInfoServiceApi.findShopperConfigByShopperId(shopper.getId(), "CTR_VIP_CHAIN_STORE");
        waimaiInfo.setIsChainStore(Integer.parseInt(Optional.ofNullable(isChainStore).orElse(0).toString()));
        //配送时间
        waimaiInfo.setReachTime(createWaimaiEntryDto.getReachTime());
        waimaiInfo.setStartDeliveryTime(createWaimaiEntryDto.getStartDeliveryTime());
        waimaiInfo.setEndDeliveryTime(createWaimaiEntryDto.getEndDeliveryTime());
        //订单序号
        waimaiInfo.setOrderSeq(shopperInfoServiceApi.updateOrderSeq(shopper.getId(), 0));
        //初始化金额为空的字段，修改为0 优惠金额
        waimaiInfo.setPromotionPrice(0.0);

        // 获取餐具费
        double boxNum = createWaimaiEntryDto.getPeopleNumber();
        double totalBoxPrice = Arith.mul(boxNum,shopperConfigExt.getBoxPrice());
        // 获取打包费
        double bagPrice = shopperConfigExt.getBagPrice();

        //存储item信息
        Map<String, Object> itemMap = saveItem(waimaiInfo, goodsCartList, bagPrice, createWaimaiEntryDto, thirdUserInfo, 0, totalBoxPrice,null);
        //totalPrice（已含有打包费）
        double totalPrice = itemMap.get("totalPrices") == null ? 0.0d : (double) itemMap.get("totalPrices");
        double totalOriginalPrice = itemMap.get("totalOriginalPrice") == null ? 0.0d : (double) itemMap.get("totalOriginalPrice");
//        double boxTotalPrice = itemMap.get("boxTotalPrice") == null ? 0.0d : (double) itemMap.get("boxTotalPrice");
        double bagTotalPrice = itemMap.get("bagTotalPrice") == null ? 0.0d : (double) itemMap.get("bagTotalPrice");

        List<WaimaiItemExtend> waimaiItems = itemMap.get("waimaiItem") == null ? null : (List<WaimaiItemExtend>)itemMap.get("waimaiItem");
        //外卖模式otherPrice = 配送：餐盒费+配送费+打包费 | 自提：打包费
        //开始结束配送时间相同为立即配送
        double otherPrice = 0D;
        if(Utils.isEmpty(createWaimaiEntryDto.getEndDeliveryTime())  && Utils.isEmpty(createWaimaiEntryDto.getStartDeliveryTime())){
            otherPrice = bagTotalPrice;
        }else{
            otherPrice = Arith.add(Arith.add(deliveryPay,totalBoxPrice),bagTotalPrice);
        }
        waimaiInfo.setOtherPrice(otherPrice);
        //因为在saveItem操作中totalPrice已经包含了bagPrice
        waimaiInfo.setTotalPrice(Arith.add(totalPrice,Arith.sub(otherPrice,bagTotalPrice)));
        waimaiInfo.setOriginalPrice(Arith.add(totalOriginalPrice,Arith.sub(otherPrice,bagTotalPrice)));
        waimaiInfo.setItems(waimaiItems);
        waimaiInfo = waimaiServiceApi.calcPromotionPrice(waimaiInfo.getItems(), waimaiInfo, createWaimaiEntryDto, shopperConfigExt);

        return waimaiInfo;
    }

    @Override
    public CoreResponse<Object> findAllOrdersByShop(String memberUid, String appId, Long shopId, String storeName, Integer outSupportId, Integer pageNo, Integer pageSize, String buyerId) {
        CoreResponse<Object> ordersRes = new CoreResponse<>();
        ordersRes.setCode(StatusInfo.SUCCESS.getCode());
        ordersRes.setMsg("查询成功");
        List<Object> list = new LinkedList<>();
        Map<String, Object> dataMap = new HashMap<>(2);
        dataMap.put("count",list.size());
        dataMap.put("list",list);
        ordersRes.setData(dataMap);

        List<String> buyerIds = new ArrayList<>();
        if(!Utils.isEmpty(memberUid)){
            buyerIds = shopperInfoServiceApi.getThirdUserInfoByMemberUid(memberUid);
        }else {
            buyerIds.add(buyerId);
        }
        if(Utils.isEmpty(buyerIds)){
            ordersRes.setMsg("查询失败，用户信息不存在");
            ordersRes.setCode(StatusInfo.NORESOURCE.getCode());
            return ordersRes;
        }
        Map<String,Object> data = null;
        if(!Utils.isEmpty(shopId)){
            data = waimaiServiceApi.findAllOrdersByShop(shopId, storeName, outSupportId, pageNo, pageSize, buyerIds);
            ordersRes.setData(data);
        }else if(!Utils.isEmpty(appId)){
            List<String> configKey =  shopperInfoServiceApi.getMiniConfigChannelAndMiniTypeKey(appId);
            if(Utils.isEmpty(configKey)){
                ordersRes.setCode(StatusInfo.NORESOURCE.getCode());
                ordersRes.setMsg("查询失败");
                return ordersRes;
            }
            List<Long> storeIds = shopperInfoServiceApi.getShopIdListByConfigKey(configKey,appId);
            if(Utils.isEmpty(storeIds)){
                ordersRes.setMsg("查询失败");
                ordersRes.setCode(StatusInfo.NORESOURCE.getCode());
                return ordersRes;
            }
            //手动分页
            data = waimaiServiceApi.findAllOrders(appId,storeName, outSupportId, pageNo, pageSize, buyerIds);
            LinkedList<AllOrdersByShopVo> dataList = new LinkedList<>();
            LinkedList<AllOrdersByShopVo> resultDataList = new LinkedList<>();
            //mini配置storeId

            List<AllOrdersByShopVo> orderList = (List<AllOrdersByShopVo>) data.get("list");
            for (AllOrdersByShopVo order : orderList){
                for(Long sId : storeIds){
                    if(order.getStoreId().equals(sId)){
                        dataList.add(order);
                    }
                }
            }
            int startNo = (pageNo - 1) * pageSize;
            int size =  pageNo * pageSize;
            int endNo = size > dataList.size() ? dataList.size() : size;
            for (int i = startNo; i < endNo;i++) {
                resultDataList.add(dataList.get(i));
            }
            data.put("count",dataList.size());
            data.put("list",resultDataList);
            ordersRes.setData(data);
        }
        logger.info("ordersRes:{}",data);
        return ordersRes;
    }

    /*
     *<pre>
     * 说    明: 优惠券选中更新订单优惠信息
     * 涉及版本:
     * 创 建 者: YangYangjun
     * 日    期: 2020-04-17 18:46
     *</pre>
     **/
    @Override
    public CoreResponse<Object> promoteOrder(PromoteOrderDto promoteOrder) throws Exception {
        CoreResponse<Object> response = new CoreResponse<>();
        //是否享受会员价配置查询
        ShopperConfig shopperConfig = shopperInfoServiceApi.getShopperConfig(promoteOrder.getStoreId(), "SET_GOODS_USER_VIP_PRICE_MODE");
        ShopperConfigExtend shopperConfigExtend = new ShopperConfigExtend();
        if(shopperConfig != null){
            shopperConfigExtend.setSetGoodsUserVipPriceMode(Integer.valueOf(shopperConfig.getPropValue()));
        }else {
            shopperConfigExtend.setSetGoodsUserVipPriceMode(Constants.SetGoodsUserVipPriceMode.VIP_MEMBER.getValue());
        }
        Map<String, Object> resultMap = new LinkedHashMap<>();
        //单个订单更新
        if(Constants.PromoteMemberRule.SINGLE_ORDER.getValue().equals(promoteOrder.getPromoteMemberRule())){
            WaimaiExtend waimaiExtend = waimaiServiceApi.getWaimaiAndDetailByOrderNum(promoteOrder.getOrderNum());
            if(waimaiExtend == null
                    || (!Constants.orderStatus.STATUS_MINUSONE.getValue().equals(waimaiExtend.getOrderStatus())
                    && !Constants.orderStatus.STATUS_ONE.getValue().equals(waimaiExtend.getOrderStatus()))){
                response.setSubMsg("订单信息不存在");
                response.setStatusInfo(StatusInfo.NORESOURCE);
                return response;
            }
            waimaiExtend = promoteSignleWaimai(waimaiExtend, promoteOrder, shopperConfigExtend);

            resultMap.put("orderNum",waimaiExtend.getOrderNum());
            resultMap.put("totalPrice",waimaiExtend.getTotalPrice());
            resultMap.put("promotionPrice",waimaiExtend.getPromotionPrice());
            resultMap.put("originalPrice",waimaiExtend.getOriginalPrice());

            response.setData(resultMap);
            response.setSubMsg("更新优惠信息成功");
            response.setStatusInfo(StatusInfo.SUCCESS);
            return response;
        }else { //多订单更新
            String buyerId = promoteOrder.getBuyerId();
            //查询一个礼拜内
            List<WaimaiExtend> unPaidEffectiveOrders = waimaiServiceApi.getWaimaiByBuyerIdInUnPaidEffective(buyerId);
            if(!Utils.isEmpty(unPaidEffectiveOrders)){
                for (WaimaiExtend waimaiExtend : unPaidEffectiveOrders) {
                    promoteSignleWaimai(waimaiExtend, promoteOrder, shopperConfigExtend);
                }
                response.setSubMsg("更新优惠信息成功");
                response.setStatusInfo(StatusInfo.SUCCESS);
                return response;
            }
        }
        return response;
    }

    //单条优惠记录更新
    private WaimaiExtend promoteSignleWaimai(WaimaiExtend waimaiExtend,PromoteOrderDto promoteOrder,ShopperConfigExtend shopperConfigExtend){
        List<WaimaiItemExtend> waimaiItemExtends = waimaiExtend.getItems();
//        if(promoteOrder.getVouchers() != null && promoteOrder.getVouchers().size() > 0){
//            Map<String, Object> calcResultMap = waimaiServiceApi.calcPromotionPrice(waimaiItemExtends, waimaiExtend, promoteOrder.getVouchers(), promoteOrder.getMemberId());
//            logger.info("优惠券返回信息:"+calcResultMap.toString());
//            waimaiExtend = (WaimaiExtend) calcResultMap.get("waimai");
////            waimaiItemExtends = (List<WaimaiItemExtend>) calcResultMap.get("waimaiItems");
//
//        }else{
//            //未使用优惠券，恢复订单原价信息
//            waimaiExtend.setTotalPrice(waimaiExtend.getOriginalPrice());
//            waimaiExtend.setPromotionPrice(0D);
//            waimaiExtend.setPromotionName(null);
//
//            for (WaimaiItemExtend item : waimaiItemExtends) {
//                item.setBuyPrice(item.getOriginalPrice());
//                item.setPromotionPrice(0D);
//                item.setPromotionName(null);
//            }
//        }


        CreateWaimaiEntryDto createWaimaiEntryVO = new CreateWaimaiEntryDto();
        createWaimaiEntryVO.setVouchers(promoteOrder.getVouchers());
        createWaimaiEntryVO.setMemberId(promoteOrder.getMemberId());
        createWaimaiEntryVO.setIsConsumePoints(promoteOrder.getIsConsumePoints());
        createWaimaiEntryVO.setUid(promoteOrder.getUid());
        createWaimaiEntryVO.setIsVip(promoteOrder.getIsVip());
        waimaiExtend = waimaiServiceApi.calcPromotionPrice(waimaiItemExtends, waimaiExtend, createWaimaiEntryVO,shopperConfigExtend);
        // 20200610 会员使用会员积分服务
        // 支付类型编码
//        double totalPay = payMotionApi.consumePointsInit(waimaiExtend,promoteOrder.getIsConsumePoints());
//        waimaiExtend.setTotalPrice(totalPay);
        logger.info("优惠券返回信息:"+waimaiExtend.toString());

        //非会员清空item会员价信息
        if(Utils.isEmpty(promoteOrder.getMemberId())){
            for (WaimaiItem item : waimaiItemExtends) {
                if(!Utils.isEmpty(item.getMemberPrice())){
                    item.setMemberPrice(null);
                    waimaiServiceApi.updateWaimaiItem(item);
                }
            }
        }

        if(waimaiItemExtends != null && waimaiItemExtends.size() > 0){
            waimaiServiceApi.updateWaimai(waimaiExtend);
        }

        return waimaiExtend;
    }



    public Map<String, Object> getTakeOutBusinessStatus(Integer storeId,Integer takeOutPeriodType,
                                                        Date date) {
        Map<String,Object> result = new HashMap<String, Object>();
        try{
            boolean flag = false;
            String weekPeriod = "";
            String dayPeriod = "";
            List<String>  dayPeriods = new ArrayList<String>();
            if(null==takeOutPeriodType || new Integer(0).equals(takeOutPeriodType)){
                weekPeriod = "1,2,3,4,5,6,7";
                Map<String,Object> shop = shopperInfoServiceApi.getBusinessTime(storeId);
                if(null==shop || null==shop.get("businessTime") || Utils.isEmpty(shop.get("businessTime"))){
                    dayPeriod = "00:00-23:59";	//商家后台设置不了24:00的营业时间
                }else{
                    dayPeriod = shop.get("businessTime").toString();
                    dayPeriod = dayPeriod.replaceAll("~", "-");
                }
                if(dayPeriod.contains(",")){
                    dayPeriods = Arrays.asList(dayPeriod.split(","));
                }else{
                    dayPeriods.add(dayPeriod);
                }
                for (String str : dayPeriods) {
                    if(Utils.matchTimeTemplate(date, weekPeriod, str.split("-")[0], str.split("-")[1])){
                        flag = true;
                        break;
                    }
                }
            }else{
                List<Map<String,Object>> list = shopperInfoServiceApi.findShopPeriod(storeId);
                if(Utils.isEmpty(list)){
                    result.put("success", false);
                    result.put("code", "40005");
                    return result;
                }
                for(Map<String,Object> periodResult : list){
                    if(null==periodResult || null==periodResult.get("weekPeriod") || null==periodResult.get("dayPeriod")
                            || Utils.isEmpty(periodResult.get("weekPeriod").toString()) || Utils.isEmpty(periodResult.get("dayPeriod").toString())){
                        result.put("success", false);
                        result.put("code", "40005");
                        return result;
                    }
                    weekPeriod = periodResult.get("weekPeriod").toString();
                    dayPeriod = periodResult.get("dayPeriod").toString();
                    if(dayPeriod.contains(",")){
                        dayPeriods = Arrays.asList(dayPeriod.split(","));
                    }else{
                        dayPeriods.add(dayPeriod);
                    }
                    for (String str : dayPeriods) {
                        if(Utils.matchTimeTemplate(date, weekPeriod, str.split("-")[0], str.split("-")[1])){
                            flag = true;
                            break;
                        }
                    }
                }
            }
            result.put("flag", flag);
            result.put("success", true);
            result.put("code", "10000");
            return result;
        }catch(Exception e){
            e.printStackTrace();
            result.put("success", false);
            result.put("code", "40005");
            return result;
        }
    }

    public Map<String,Object> getDeliveryPay(TakeOutConfig config, TakeOutBilling billing,
                                             Double distance) {
        Map<String,Object> result = new HashMap<String, Object>();
        try{
            //超出商家配送范围
            if(null == config.getMaxTakeOutDistance() || distance > config.getMaxTakeOutDistance()){
                result.put("success", false);
                result.put("code", "40001");
                return result;
            }
            if(null == config.getTakeOutBillingType() ||
                    !(new Integer(0).equals(config.getTakeOutBillingType()) || new Integer(1).equals(config.getTakeOutBillingType()))){
                result.put("success", false);
                result.put("msg", "数据异常");
                result.put("code", "40000");
                return result;
            }
            Double deliveryPay = 0d;
            if(new Integer(0).equals(config.getTakeOutBillingType())){
                //按区域固定配送费
                if(Utils.isEmpty(billing.getTakeOutRange()) || Utils.isEmpty(billing.getTakeOutPrice())){
                    result.put("success", false);
                    result.put("code", "40000");
                    return result;
                }
                String[] rangeArr = billing.getTakeOutRange().split(",");
                String[] priceArr = billing.getTakeOutPrice().split(",");
                int i = 0;
                for(String s : rangeArr){
                    i++;
                    if(distance <= Double.valueOf(s)){
                        deliveryPay = Double.valueOf(priceArr[i-1]);
                        break;
                    }
                }
                result.put("success", true);
                result.put("code", "10000");
                result.put("deliveryPay", deliveryPay);
                return result;
            }else{
                //按距离阶梯配送
                if(null == billing.getStandardKilometre() || null == billing.getBeyondKilometre() ||
                        null == billing.getBeyondPrice()){
                    result.put("success", false);
                    result.put("code", "40000");
                    result.put("msg", "数据异常");
                    return result;
                }
                //如果距离未超过标准配送范围
                if(distance < billing.getStandardKilometre()){
                    deliveryPay = billing.getStandardPrice();
                }else{
                    //配送费 = 标准价格+[(距离 - 标准范围)/每增加公里数]*增加配送费
                    deliveryPay = Arith.add(billing.getStandardPrice(),
                            Arith.mul(
                                    Arith.div(
                                            Arith.sub(distance, billing.getStandardKilometre()),
                                            billing.getBeyondKilometre()),
                                    billing.getBeyondPrice()));
                }
                deliveryPay = Arith.round(deliveryPay, 2);
                result.put("success", true);
                result.put("code", "10000");
                result.put("deliveryPay", deliveryPay);
                return result;
            }
        }catch(Exception e){
            e.printStackTrace();
            result.put("success", false);
            result.put("code", "40005");
            return result;
        }
    }
}
